pixelkiln 0.92.2 → 0.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -67,8 +67,8 @@ function exitCodeFor(err) {
67
67
  }
68
68
 
69
69
  // src/cli/main.ts
70
- import { existsSync as existsSync39 } from "fs";
71
- import { readFile as readFile36 } from "fs/promises";
70
+ import { existsSync as existsSync41 } from "fs";
71
+ import { readFile as readFile37 } from "fs/promises";
72
72
 
73
73
  // src/cli/args.ts
74
74
  import path from "path";
@@ -102,6 +102,8 @@ var VALUE_FLAGS = [
102
102
  "--min-grid-confidence",
103
103
  "--reviewer",
104
104
  "--note",
105
+ "--source",
106
+ "--object-id",
105
107
  "--model-root",
106
108
  "--generation",
107
109
  "--quantize",
@@ -135,11 +137,13 @@ var BOOL_FLAGS = [
135
137
  "--edit",
136
138
  "--refresh",
137
139
  "--no-editor",
138
- "--game-pack"
140
+ "--game-pack",
141
+ "--local"
139
142
  ];
140
143
  var COMMANDS = [
141
144
  "init",
142
145
  "plan",
146
+ "hash",
143
147
  "doctor",
144
148
  "gen",
145
149
  "submit",
@@ -415,6 +419,9 @@ function parseArgs(argv) {
415
419
  edit: rest.includes("--edit"),
416
420
  noEditor: rest.includes("--no-editor"),
417
421
  refresh: rest.includes("--refresh"),
422
+ local: rest.includes("--local"),
423
+ source: get("--source"),
424
+ objectId: get("--object-id"),
418
425
  from: get("--from"),
419
426
  out: get("--out"),
420
427
  generator: get("--generator"),
@@ -482,6 +489,8 @@ Commands
482
489
  --generation <n|hash> brings a previous generation back instead.
483
490
  history List the generations each asset has replaced and can restore.
484
491
  adopt Match existing account objects to files already in the repo.
492
+ --local records them offline (no key): --source, --note, --object-id, --dry-run.
493
+ hash Print each asset's spec hash, file hash and would-be lock entry (offline).
485
494
  accept Keep existing art after a style reword. Re-baseline, do not regenerate.
486
495
  salvage Triage account objects no lockfile claims. Recovers usable art.
487
496
  One session per matching style unless --style forces a single one.
@@ -978,6 +987,17 @@ function candidateCount(size) {
978
987
  if (size <= 170) return 4;
979
988
  return 1;
980
989
  }
990
+ function uiElementCandidateCount(size) {
991
+ if (size <= 32) return 64;
992
+ if (size <= 35) return 49;
993
+ if (size <= 41) return 36;
994
+ if (size <= 50) return 25;
995
+ if (size <= 64) return 16;
996
+ if (size <= 84) return 9;
997
+ if (size === 85) return 16;
998
+ if (size <= 170) return 4;
999
+ return 1;
1000
+ }
981
1001
  function generationCost(width, height, generator = "map") {
982
1002
  if (generator === "vfx") return 0;
983
1003
  if (generator === "map" || generator === "pixflux") return 1;
@@ -994,6 +1014,16 @@ function proTierCost(width, height) {
994
1014
  if (px <= 102400) return PRO_TIER_PRICES[1];
995
1015
  return PRO_TIER_PRICES[2];
996
1016
  }
1017
+ function pixMiniMaxCost(width, height, frames, enhancePrompt = false) {
1018
+ const f = width * height * Math.max(1, frames) / 4096;
1019
+ let units;
1020
+ if (f <= 8) units = 1;
1021
+ else if (f <= 16) units = 1 + (f - 8) / 8;
1022
+ else if (f <= 40) units = 2 + (f - 16) / 6;
1023
+ else units = 6 + (f - 40) / 6;
1024
+ const base = Math.max(1, Math.ceil(units - 1e-9));
1025
+ return enhancePrompt ? base + 0.05 : base;
1026
+ }
997
1027
  function tilesCost(tileSize, variations) {
998
1028
  const px = tileSize * tileSize * Math.max(1, variations);
999
1029
  if (px <= 1024) return PRO_TIER_PRICES[0];
@@ -2491,7 +2521,17 @@ var LockEntrySchema = z.object({
2491
2521
  /** Generations this entry replaced, newest first; see LockHistoryEntrySchema. */
2492
2522
  history: z.array(LockHistoryEntrySchema).optional(),
2493
2523
  /** Post-processing applied to the recorded outputs; absent when the bytes are the provider's. */
2494
- postprocess: PostprocessSchema.optional()
2524
+ postprocess: PostprocessSchema.optional(),
2525
+ /**
2526
+ * Set when the entry records art made outside pixelkiln (the PixelLab MCP, a
2527
+ * hand edit, another tool) and brought in with `adopt --local`: nothing was
2528
+ * submitted, so jobId and cost are empty. Absent on generated entries.
2529
+ */
2530
+ imported: z.object({
2531
+ source: z.string().min(1),
2532
+ note: z.string().optional(),
2533
+ importedAt: z.string()
2534
+ }).strict().optional()
2495
2535
  });
2496
2536
  var LockSchema = z.object({
2497
2537
  version: z.literal(2),
@@ -5333,7 +5373,7 @@ async function confirm(question, auto) {
5333
5373
 
5334
5374
  // src/cli/commands/account.ts
5335
5375
  import path25 from "path";
5336
- import { existsSync as existsSync18 } from "fs";
5376
+ import { existsSync as existsSync20 } from "fs";
5337
5377
 
5338
5378
  // src/env.ts
5339
5379
  import { readFileSync, existsSync as existsSync6 } from "fs";
@@ -7570,10 +7610,10 @@ var PixelLabClient = class {
7570
7610
  * limited to 400x400 and no style reference. Like a revision, this hands
7571
7611
  * back a plain background job with no resource of its own; unlike a
7572
7612
  * revision, one call returns several candidate images to pick from (the
7573
- * same 4/16/64-by-size tiering as `1dir`), not a single result, and its
7574
- * completed shape has not been exercised live yet — `pollImagePro` in
7575
- * pixellab.ts fails loudly rather than guess if `last_response.images`
7576
- * turns out not to be the real field name.
7613
+ * same 4/16/64-by-size tiering as `1dir`), not a single result. It has run
7614
+ * live (a 64x64 call billed 10, October 2026); `pollImagePro` in
7615
+ * pixellab.ts still fails loudly rather than guess if `last_response.images`
7616
+ * is not the field name.
7577
7617
  *
7578
7618
  * Reference images and a style image (`reference_images`, `style_image` +
7579
7619
  * `style_options`) exist on this endpoint but are not modeled here yet.
@@ -7684,7 +7724,8 @@ var PixelLabClient = class {
7684
7724
  * guided by an optional concept image and a natural-language color
7685
7725
  * palette. A plain background job; unlike `/create-ui-asset` there is no
7686
7726
  * piece/element layout, and sizes start at 16px instead of 192. Its
7687
- * completed shape has not been exercised live; `pollUiElement` reads it
7727
+ * completed shape came back as a list of candidates on a live
7728
+ * 32x32 call (64 of them, billed 10); `pollUiElement` still reads it
7688
7729
  * defensively.
7689
7730
  */
7690
7731
  async generateUiV2(args) {
@@ -7930,11 +7971,10 @@ var PixelLabClient = class {
7930
7971
  * no PixelLab character/object resource required — unlike `animateCharacter`
7931
7972
  * / `animateObject`, `firstFrame` is whatever bytes the caller has on hand.
7932
7973
  * A plain background job, like every other PixelLab async submission;
7933
- * unlike `inpaintV3`/`editImagesV2`, its completed shape has not been
7934
- * exercised against a live account (request/response fields here come from
7935
- * the live OpenAPI document, not an observed call — `pollAnimateRevision`
7936
- * in pixellab.ts checks several plausible field names for the frame list
7937
- * defensively, the same as `pollRevision` already does for image edits).
7974
+ * like `inpaintV3`/`editImagesV2`, it has run live (November 2026, a
7975
+ * 64x64 call of 4 frames billed 1 and returned 5 frames); `pollAnimateRevision`
7976
+ * in pixellab.ts still checks several plausible field names for the frame
7977
+ * list defensively, the same as `pollRevision` does for image edits.
7938
7978
  */
7939
7979
  async animateWithTextV3(args) {
7940
7980
  const body = { first_frame: args.firstFrame, action: args.action };
@@ -8018,8 +8058,8 @@ var PixelLabClient = class {
8018
8058
  * `runEstimateSkeleton` in `src/cli/commands`) so the only PixelLab
8019
8059
  * endpoint composed into `animate-with-skeleton-v3`'s submission is that
8020
8060
  * one endpoint itself, not two unverified calls chained together.
8021
- * Synchronous per this endpoint's own framing; unverified against a live
8022
- * account (see `EstimateSkeletonResponseSchema`'s own caveat).
8061
+ * Synchronous, and it has run live (October 2026; see
8062
+ * `EstimateSkeletonResponseSchema`).
8023
8063
  */
8024
8064
  async estimateSkeleton(args) {
8025
8065
  const body = { image: { type: "base64", base64: args.image.base64, format: args.image.format } };
@@ -9195,12 +9235,15 @@ var PixelLabProvider = class _PixelLabProvider {
9195
9235
  const width = spec.revision.sourceWidth ?? spec.width;
9196
9236
  const height = spec.revision.sourceHeight ?? spec.height;
9197
9237
  const side = spec.revision.mode === "edit-animation" ? Math.ceil(Math.sqrt(Math.max(1, spec.revision.sourceMembers?.length ?? 1))) : 1;
9198
- return { unit: "generations", amount: generationCost(width * side, height * side, "1dir"), candidates: 1 };
9238
+ return { unit: "generations", amount: proTierCost(width * side, height * side), candidates: 1 };
9199
9239
  }
9200
9240
  if (spec.revision?.mode === "animate" || spec.revision?.mode === "animate-pixminimax") {
9201
9241
  const width = spec.revision.sourceWidth ?? spec.width;
9202
9242
  const height = spec.revision.sourceHeight ?? spec.height;
9203
9243
  const frames = spec.revision.frames ?? 8;
9244
+ if (spec.revision.mode === "animate-pixminimax") {
9245
+ return { unit: "generations", amount: pixMiniMaxCost(width, height, frames, spec.revision.enhancePrompt), candidates: 1 };
9246
+ }
9204
9247
  const base = Math.max(1, Math.ceil(width * height * frames / 65536));
9205
9248
  return { unit: "generations", amount: spec.revision.enhancePrompt ? base + 0.05 : base, candidates: 1 };
9206
9249
  }
@@ -9231,7 +9274,7 @@ var PixelLabProvider = class _PixelLabProvider {
9231
9274
  return {
9232
9275
  unit: "generations",
9233
9276
  amount: generationCost(spec.width, spec.height, spec.generator),
9234
- candidates: spec.generator === "1dir" || spec.generator === "imagePro" ? candidateCount(spec.size) : 1
9277
+ candidates: spec.generator === "1dir" || spec.generator === "imagePro" ? candidateCount(spec.size) : spec.generator === "uiElement" ? uiElementCandidateCount(spec.size) : 1
9235
9278
  };
9236
9279
  }
9237
9280
  validate(spec, styleImages) {
@@ -10919,13 +10962,13 @@ var PixelLabProvider = class _PixelLabProvider {
10919
10962
  async pollVfx(jobId, context) {
10920
10963
  const dir = _PixelLabProvider.cacheDir("vfx");
10921
10964
  const sidecar = path14.join(dir, `${jobId}.json`);
10922
- const cached = () => {
10965
+ const cached2 = () => {
10923
10966
  if (!existsSync9(sidecar)) return null;
10924
10967
  const facts2 = JSON.parse(readFileSync2(sidecar, "utf8"));
10925
10968
  const files2 = Array.from({ length: facts2.count }, (_, index) => path14.join(dir, `${jobId}-${index}.png`));
10926
10969
  return files2.every((file) => existsSync9(file)) ? { facts: facts2, files: files2 } : null;
10927
10970
  };
10928
- let found = cached();
10971
+ let found = cached2();
10929
10972
  const recorded = context?.metadata?.vfx;
10930
10973
  let artistDone;
10931
10974
  if (!found && recorded?.artist) {
@@ -10945,11 +10988,11 @@ var PixelLabProvider = class _PixelLabProvider {
10945
10988
  }
10946
10989
  artistDone.billed = billedFromUsage(job.usage);
10947
10990
  }
10948
- found = cached();
10991
+ found = cached2();
10949
10992
  } else if (!found && recorded?.downloadBase && Array.isArray(recorded.files)) {
10950
10993
  const exported = recorded;
10951
10994
  await this.cacheVfxFrames(jobId, exported, workbenchVfxUrls(exported));
10952
- found = cached();
10995
+ found = cached2();
10953
10996
  }
10954
10997
  if (!found) {
10955
10998
  return {
@@ -11081,15 +11124,15 @@ var PixelLabProvider = class _PixelLabProvider {
11081
11124
  * `pollRevision` above, but completing with an ORDERED FRAME LIST instead
11082
11125
  * of a single image — the same `review-set` shape `pollCharacterAnimation`
11083
11126
  * returns, minus any character/object resource to look the result up on
11084
- * (there is none; this operates on a loose image). Unlike every other
11085
- * PixelLab call this adapter makes, the completed shape for
11086
- * `/animate-with-text-v3`/`/animate-pixminimax` has never been exercised
11087
- * against a live account — the checks below are an informed guess (hosted
11088
- * URLs under a plausible key name, the same `storage_urls.frames` shape
11089
- * character animations use, or inline base64 per frame, decoded to a local
11090
- * cache file the same way `pollRevision`'s single-image case already is)
11091
- * rather than an observed shape, and fail loudly, naming the keys actually
11092
- * received, for whatever the real shape turns out to be.
11127
+ * (there is none; this operates on a loose image). Both
11128
+ * `/animate-with-text-v3` and `/animate-pixminimax` have run live
11129
+ * (November 2026) and the completed jobs were read correctly. The checks
11130
+ * below stay defensive (hosted URLs under a plausible key name, the same
11131
+ * `storage_urls.frames` shape character animations use, or inline base64
11132
+ * per frame, decoded to a local cache file the same way `pollRevision`'s
11133
+ * single-image case is) and fail loudly, naming the keys actually
11134
+ * received, if a shape ever differs. PixMiniMax includes the input frame,
11135
+ * so a set holds the requested count plus one.
11093
11136
  */
11094
11137
  async pollAnimateRevision(jobId, context) {
11095
11138
  const job = await this.client.getBackgroundJob(jobId);
@@ -11230,7 +11273,7 @@ var PixelLabProvider = class _PixelLabProvider {
11230
11273
  }
11231
11274
  return {
11232
11275
  status: "failed",
11233
- error: `Invalid PixelLab response for imagePro job ${jobId}: completed with no recognized images array (got: ${Object.keys(done).join(", ") || "no keys"}); this endpoint's completed shape has not been exercised live yet -- update pollImagePro in src/providers/pixellab.ts with the real shape`
11276
+ error: `Invalid PixelLab response for imagePro job ${jobId}: completed with no recognized images array (got: ${Object.keys(done).join(", ") || "no keys"}); update pollImagePro in src/providers/pixellab.ts with the real shape`
11234
11277
  };
11235
11278
  }
11236
11279
  /**
@@ -12147,8 +12190,8 @@ var ScenarioClient = class {
12147
12190
  async uploadImage(image, projectId) {
12148
12191
  const bytes = Buffer.from(image.base64, "base64");
12149
12192
  const digest2 = sha256(bytes);
12150
- const cached = readUploadCache()[uploadCacheKey(this.baseUrl, projectId, digest2)];
12151
- if (cached) return cached;
12193
+ const cached2 = readUploadCache()[uploadCacheKey(this.baseUrl, projectId, digest2)];
12194
+ if (cached2) return cached2;
12152
12195
  const response = await this.call(
12153
12196
  "/assets",
12154
12197
  {
@@ -12739,7 +12782,7 @@ registerProvider({
12739
12782
 
12740
12783
  // src/manifest.ts
12741
12784
  import { readFile as readFile8 } from "fs/promises";
12742
- import { existsSync as existsSync10 } from "fs";
12785
+ import { existsSync as existsSync11 } from "fs";
12743
12786
  import path16 from "path";
12744
12787
 
12745
12788
  // src/loop-directions.ts
@@ -12835,10 +12878,31 @@ function isObject2(value) {
12835
12878
  return typeof value === "object" && value !== null && !Array.isArray(value);
12836
12879
  }
12837
12880
 
12881
+ // src/version.ts
12882
+ import { existsSync as existsSync10, readFileSync as readFileSync4 } from "fs";
12883
+ var cached;
12884
+ function pixelkilnVersion() {
12885
+ if (cached !== void 0) return cached;
12886
+ cached = null;
12887
+ for (const up of ["../package.json", "../../package.json"]) {
12888
+ const url = new URL(up, import.meta.url);
12889
+ if (!existsSync10(url)) continue;
12890
+ try {
12891
+ const pkg = JSON.parse(readFileSync4(url, "utf8"));
12892
+ if (pkg.name === "pixelkiln" && pkg.version) {
12893
+ cached = pkg.version;
12894
+ break;
12895
+ }
12896
+ } catch {
12897
+ }
12898
+ }
12899
+ return cached;
12900
+ }
12901
+
12838
12902
  // src/manifest.ts
12839
12903
  async function loadManifest(manifestPath) {
12840
12904
  const abs = path16.resolve(manifestPath);
12841
- if (!existsSync10(abs)) throw new ProjectError(`No manifest at ${abs}`);
12905
+ if (!existsSync11(abs)) throw new ProjectError(`No manifest at ${abs}`);
12842
12906
  const expansion = expandLoopDirections(JSON.parse(await readFile8(abs, "utf8")));
12843
12907
  if (expansion.issues.length) {
12844
12908
  throw new ProjectError(`Manifest at ${abs} is invalid:
@@ -12990,19 +13054,45 @@ function dependencyAssetIds(asset, styleAnchors = []) {
12990
13054
  ].filter((id) => Boolean(id))
12991
13055
  ];
12992
13056
  }
13057
+ var MAX_LISTED_MANIFEST_ISSUES = 20;
13058
+ function flattenManifestIssues(issues) {
13059
+ let unknownShape = false;
13060
+ const visit = (list) => list.flatMap((issue) => {
13061
+ if (issue.code === "invalid_union") return visit(issue.unionErrors.flatMap((error) => error.issues));
13062
+ if (issue.code === "unrecognized_keys" || issue.code === "invalid_enum_value") unknownShape = true;
13063
+ return [` ${issue.path.join(".") || "(manifest)"}: ${issue.message}`];
13064
+ });
13065
+ return { lines: [...new Set(visit(issues))], unknownShape };
13066
+ }
12993
13067
  function formatManifestIssues(issues) {
12994
- return issues.flatMap((issue) => {
12995
- if (issue.code === "invalid_union") {
12996
- return issue.unionErrors.flatMap((error) => formatManifestIssues(error.issues).split("\n"));
12997
- }
12998
- return [` ${issue.path.join(".")}: ${issue.message}`];
12999
- }).join("\n");
13068
+ const { lines, unknownShape } = flattenManifestIssues(issues);
13069
+ const entries = [...new Set(
13070
+ lines.flatMap((line) => {
13071
+ const match = /^ {2}((?:assets|styles)\.[^.:\s]+)/.exec(line);
13072
+ return match ? [match[1]] : [];
13073
+ })
13074
+ )];
13075
+ const out = [];
13076
+ const version = pixelkilnVersion();
13077
+ if (unknownShape) {
13078
+ out.push(
13079
+ ` This manifest uses fields or values pixelkiln ${version ?? "(this version)"} does not know. If it was written by a newer release, run \`npx pixelkiln@latest\` or update the install before editing it.`
13080
+ );
13081
+ }
13082
+ if (entries.length) {
13083
+ out.push(` ${entries.length} invalid entr${entries.length === 1 ? "y" : "ies"}: ${entries.slice(0, 10).join(", ")}${entries.length > 10 ? ", \u2026" : ""}`);
13084
+ }
13085
+ out.push(...lines.slice(0, MAX_LISTED_MANIFEST_ISSUES));
13086
+ if (lines.length > MAX_LISTED_MANIFEST_ISSUES) {
13087
+ out.push(` \u2026 and ${lines.length - MAX_LISTED_MANIFEST_ISSUES} more`);
13088
+ }
13089
+ return out.join("\n");
13000
13090
  }
13001
13091
  function resolveStyleInheritance(styles) {
13002
13092
  const resolved = /* @__PURE__ */ new Map();
13003
13093
  const visit = (styleId, chain) => {
13004
- const cached = resolved.get(styleId);
13005
- if (cached) return cached;
13094
+ const cached2 = resolved.get(styleId);
13095
+ if (cached2) return cached2;
13006
13096
  const cycleStart = chain.indexOf(styleId);
13007
13097
  if (cycleStart >= 0) {
13008
13098
  throw new Error(
@@ -13124,7 +13214,7 @@ async function resolveSpecs(loaded, filter) {
13124
13214
  const abs = path16.resolve(root, rel);
13125
13215
  let hit = styleImageCache.get(abs);
13126
13216
  if (!hit) {
13127
- if (!existsSync10(abs)) throw new Error(`${what} not found: ${abs}`);
13217
+ if (!existsSync11(abs)) throw new Error(`${what} not found: ${abs}`);
13128
13218
  const buf = await readFile8(abs);
13129
13219
  const metadata = imageMetadata(buf);
13130
13220
  if (!metadata) throw new Error(`${what} is not a readable PNG or JPEG: ${abs}`);
@@ -13475,7 +13565,7 @@ async function resolveSpecs(loaded, filter) {
13475
13565
  const file = memberPath(anchorSpec.outFile, "south", 0, anchorSpec.character.directions, MediaType.PNG);
13476
13566
  resolved.character = {
13477
13567
  ...resolved.character,
13478
- styleAnchor: { assetId: anchorId, spec: anchorSpec, file, sha256: existsSync10(file) ? await sha256File(file) : null }
13568
+ styleAnchor: { assetId: anchorId, spec: anchorSpec, file, sha256: existsSync11(file) ? await sha256File(file) : null }
13479
13569
  };
13480
13570
  }
13481
13571
  const characterParent = asset.state?.of ?? asset.animation?.of ?? asset.portrait?.of;
@@ -13488,7 +13578,7 @@ async function resolveSpecs(loaded, filter) {
13488
13578
  parentAssetId: characterParent,
13489
13579
  parentSpec,
13490
13580
  parentFile,
13491
- parentSha256: existsSync10(parentFile) ? await sha256File(parentFile) : null,
13581
+ parentSha256: existsSync11(parentFile) ? await sha256File(parentFile) : null,
13492
13582
  // A state and its animations keep the engine and rotations of the base.
13493
13583
  mode: resolved.character.kind === "base" ? resolved.character.mode : parentSpec.character?.mode ?? resolved.character.mode,
13494
13584
  directions: resolved.character.kind === "base" ? resolved.character.directions : parentSpec.character?.directions ?? resolved.character.directions
@@ -13526,7 +13616,7 @@ async function resolveSpecs(loaded, filter) {
13526
13616
  parentAssetId: characterParent,
13527
13617
  parentSpec,
13528
13618
  parentFile,
13529
- parentSha256: existsSync10(parentFile) ? await sha256File(parentFile) : null,
13619
+ parentSha256: existsSync11(parentFile) ? await sha256File(parentFile) : null,
13530
13620
  // A state and its animations keep the base's own rotation count.
13531
13621
  directions: resolved.objectPro.kind === "base" ? resolved.objectPro.directions : parentSpec.objectPro.directions
13532
13622
  };
@@ -13730,8 +13820,18 @@ async function resolveSpecs(loaded, filter) {
13730
13820
  providerOptionIdentity,
13731
13821
  providerInputIdentities.get(assetId)
13732
13822
  );
13733
- activeProvider.validate?.(resolved, resolvedImages);
13734
- const estimate = validateCostEstimate(activeProvider.id, activeProvider.estimate(resolved));
13823
+ let estimate;
13824
+ try {
13825
+ activeProvider.validate?.(resolved, resolvedImages);
13826
+ estimate = validateCostEstimate(activeProvider.id, activeProvider.estimate(resolved));
13827
+ } catch (error) {
13828
+ const message6 = error instanceof Error ? error.message : String(error);
13829
+ if (message6.includes(`assets.${assetId}`)) throw error;
13830
+ throw new Error(
13831
+ `assets.${assetId} (style "${styleId}", ${resolved.width}x${resolved.height}): ${message6}`,
13832
+ { cause: error }
13833
+ );
13834
+ }
13735
13835
  resolved.cost = estimate.amount;
13736
13836
  resolved.costUnit = estimate.unit;
13737
13837
  resolved.candidates = estimate.candidates;
@@ -13815,7 +13915,7 @@ async function resolveVfxShape(root, assetId, vfx, defaultName) {
13815
13915
  let recordedSprite;
13816
13916
  if (vfx.recipe) {
13817
13917
  const file = path16.resolve(root, vfx.recipe);
13818
- if (!existsSync10(file)) throw new Error(`assets.${assetId}.vfx.recipe: VFX recipe not found: ${file}`);
13918
+ if (!existsSync11(file)) throw new Error(`assets.${assetId}.vfx.recipe: VFX recipe not found: ${file}`);
13819
13919
  const read = await readVfxRecipe(file).catch((error) => {
13820
13920
  throw new Error(`assets.${assetId}.vfx.recipe: ${error instanceof Error ? error.message : String(error)}`);
13821
13921
  });
@@ -13842,7 +13942,7 @@ async function resolveVfxShape(root, assetId, vfx, defaultName) {
13842
13942
  };
13843
13943
  }
13844
13944
  async function optionalRevisionImage(file, label, requiredFormat) {
13845
- if (!existsSync10(file)) return null;
13945
+ if (!existsSync11(file)) return null;
13846
13946
  const bytes = await readFile8(file);
13847
13947
  const metadata = imageMetadata(bytes);
13848
13948
  if (!metadata) throw new Error(`${label} is not a readable PNG or JPEG: ${file}`);
@@ -13852,7 +13952,7 @@ async function optionalRevisionImage(file, label, requiredFormat) {
13852
13952
  return { hash: sha256(bytes), ...metadata };
13853
13953
  }
13854
13954
  async function optionalSkeletonSet(file) {
13855
- if (!existsSync10(file)) return null;
13955
+ if (!existsSync11(file)) return null;
13856
13956
  const bytes = await readFile8(file);
13857
13957
  let json;
13858
13958
  try {
@@ -13863,17 +13963,17 @@ async function optionalSkeletonSet(file) {
13863
13963
  return { hash: sha256(bytes), skeleton: parseSkeletonSet(json, file) };
13864
13964
  }
13865
13965
  async function revisionSourceMembers(stem, label) {
13866
- if (existsSync10(stem)) return null;
13966
+ if (existsSync11(stem)) return null;
13867
13967
  const at = (role) => memberPath(stem, role, 0, 2, MediaType.PNG);
13868
13968
  let roles = [];
13869
13969
  for (const set of [CHARACTER_DIRECTIONS_8, CHARACTER_DIRECTIONS_4]) {
13870
- if (set.every((direction) => existsSync10(at(direction)))) {
13970
+ if (set.every((direction) => existsSync11(at(direction)))) {
13871
13971
  roles = [...set];
13872
13972
  break;
13873
13973
  }
13874
13974
  }
13875
13975
  if (!roles.length) {
13876
- for (let index = 0; existsSync10(at(`frame-${String(index).padStart(2, "0")}`)); index++) {
13976
+ for (let index = 0; existsSync11(at(`frame-${String(index).padStart(2, "0")}`)); index++) {
13877
13977
  roles.push(`frame-${String(index).padStart(2, "0")}`);
13878
13978
  }
13879
13979
  }
@@ -14032,7 +14132,7 @@ async function resolveObjectProShape(assetId, asset, style, kind, files) {
14032
14132
  }
14033
14133
 
14034
14134
  // src/pipeline/fetch.ts
14035
- import { existsSync as existsSync11, readFileSync as readFileSync4 } from "fs";
14135
+ import { existsSync as existsSync12, readFileSync as readFileSync5 } from "fs";
14036
14136
  import { mkdir as mkdir6, readFile as readFile9, rename as rename4, rm as rm4, writeFile as writeFile6 } from "fs/promises";
14037
14137
  import path17 from "path";
14038
14138
  async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
@@ -14052,15 +14152,15 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14052
14152
  if (spec && e.specHash === spec.specHash && e.outputs.length && !postprocessCurrent(e, spec)) {
14053
14153
  return Boolean(opts.force) || e.outputs.every((output) => {
14054
14154
  const file = resolveOutputPath(output.path, spec.root);
14055
- return existsSync11(file) && sha256(readFileSync4(file)) === output.sha256;
14155
+ return existsSync12(file) && sha256(readFileSync5(file)) === output.sha256;
14056
14156
  });
14057
14157
  }
14058
14158
  if (!opts.repair) return false;
14059
14159
  if (e.outputs.length === 0 || !spec) return true;
14060
14160
  return e.outputs.some((output) => {
14061
14161
  const file = resolveOutputPath(output.path, spec.root);
14062
- if (!existsSync11(file)) return true;
14063
- const current = sha256(readFileSync4(file));
14162
+ if (!existsSync12(file)) return true;
14163
+ const current = sha256(readFileSync5(file));
14064
14164
  if (current === output.sha256) return false;
14065
14165
  return Boolean(opts.force) || (e.supersededOutputs ?? []).some((old) => old.sha256 === current);
14066
14166
  });
@@ -14150,7 +14250,7 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14150
14250
  }
14151
14251
  let raw = null;
14152
14252
  let final = null;
14153
- if (existsSync11(target)) {
14253
+ if (existsSync12(target)) {
14154
14254
  const currentHash = await sha256File(target);
14155
14255
  if (recorded && currentHash === recorded.sha256) {
14156
14256
  if (!fresh && !reapply) {
@@ -14296,7 +14396,7 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14296
14396
  }
14297
14397
  async function readCachedMedia(cacheDir, hash, mediaType) {
14298
14398
  const file = path17.join(cacheDir, cacheFileName(hash, mediaType));
14299
- if (!existsSync11(file)) return null;
14399
+ if (!existsSync12(file)) return null;
14300
14400
  try {
14301
14401
  const buf = await readFile9(file);
14302
14402
  if (sha256(buf) !== hash) return null;
@@ -14317,7 +14417,7 @@ async function cacheMedia(cacheDir, buf, mediaType, knownHash) {
14317
14417
  try {
14318
14418
  await rename4(tmp, file);
14319
14419
  } catch (err) {
14320
- if (!existsSync11(file)) throw err;
14420
+ if (!existsSync12(file)) throw err;
14321
14421
  } finally {
14322
14422
  await rm4(tmp, { force: true });
14323
14423
  }
@@ -14349,14 +14449,125 @@ async function pushTags(provider, specs, lock, opts = {}) {
14349
14449
  return tagged;
14350
14450
  }
14351
14451
 
14352
- // src/pipeline/adopt.ts
14452
+ // src/pipeline/import.ts
14353
14453
  import { existsSync as existsSync13 } from "fs";
14354
- import { readFile as readFile11, writeFile as writeFile8 } from "fs/promises";
14454
+ import { readFile as readFile10 } from "fs/promises";
14455
+ function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Date()) {
14456
+ const png = decodePng(bytes);
14457
+ const at = now.toISOString();
14458
+ return {
14459
+ styleId: spec.styleId,
14460
+ assetId: spec.assetId,
14461
+ specHash: spec.specHash,
14462
+ generator: spec.generator,
14463
+ prompt: spec.prompt,
14464
+ width: png.width,
14465
+ height: png.height,
14466
+ jobId: opts.objectId ?? null,
14467
+ objectId: opts.objectId ?? null,
14468
+ reviewObjectId: null,
14469
+ candidateIndex: null,
14470
+ status: "downloaded",
14471
+ error: null,
14472
+ sourceUrl: null,
14473
+ sourceUrls: [],
14474
+ outputs: [{ path: portableOutputPath(spec.outFile, spec.root), sha256: sha256(bytes) }],
14475
+ submittedAt: null,
14476
+ downloadedAt: at,
14477
+ cost: 0,
14478
+ costUnit: spec.costUnit,
14479
+ provider: spec.provider,
14480
+ imported: {
14481
+ source: opts.source ?? "external",
14482
+ ...opts.note ? { note: opts.note } : {},
14483
+ importedAt: at
14484
+ }
14485
+ };
14486
+ }
14487
+ function unimportable(spec) {
14488
+ if (spec.character) return "a character is several files; import it with account adopt";
14489
+ if (spec.vfx) return "an effect is rendered from its recipe, not imported";
14490
+ if (!spec.outFile.toLowerCase().endsWith(".png")) return "only a single PNG output can be imported";
14491
+ return null;
14492
+ }
14493
+ async function importLocal(specs, lock, lockPath, opts = {}) {
14494
+ if (opts.objectId && specs.length !== 1) {
14495
+ throw new Error(`--object-id names one object; ${specs.length} assets are selected. Narrow with --only and --style.`);
14496
+ }
14497
+ const imported = [];
14498
+ const skipped = [];
14499
+ for (const spec of specs) {
14500
+ const key = lockKey(spec.styleId, spec.assetId);
14501
+ const reason = unimportable(spec);
14502
+ if (reason) {
14503
+ skipped.push({ key, reason });
14504
+ continue;
14505
+ }
14506
+ if (!existsSync13(spec.outFile)) {
14507
+ skipped.push({ key, reason: `no file at ${spec.outFile}` });
14508
+ continue;
14509
+ }
14510
+ if (lock.entries[key] && !opts.force) {
14511
+ skipped.push({ key, reason: "already in the lockfile (use --force to replace it)" });
14512
+ continue;
14513
+ }
14514
+ let patch;
14515
+ try {
14516
+ patch = buildImportedEntry(spec, await readFile10(spec.outFile), opts);
14517
+ } catch (error) {
14518
+ skipped.push({ key, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
14519
+ continue;
14520
+ }
14521
+ if (opts.dryRun) {
14522
+ imported.push({ key, entry: patch });
14523
+ continue;
14524
+ }
14525
+ imported.push({ key, entry: upsert(lock, key, patch) });
14526
+ }
14527
+ if (!opts.dryRun && imported.length) await saveLock(lockPath, lock);
14528
+ return { imported, skipped };
14529
+ }
14530
+ async function reportSpecHashes(specs, lock) {
14531
+ const reports = [];
14532
+ for (const spec of specs) {
14533
+ const key = lockKey(spec.styleId, spec.assetId);
14534
+ let bytes = null;
14535
+ if (existsSync13(spec.outFile)) bytes = await readFile10(spec.outFile);
14536
+ let wouldImport = null;
14537
+ if (bytes && !unimportable(spec)) {
14538
+ try {
14539
+ wouldImport = buildImportedEntry(spec, bytes);
14540
+ } catch {
14541
+ wouldImport = null;
14542
+ }
14543
+ }
14544
+ const entry = lock.entries[key];
14545
+ const fileSha256 = bytes ? sha256(bytes) : null;
14546
+ const outputSha256 = entry?.outputs[0]?.sha256 ?? null;
14547
+ reports.push({
14548
+ key,
14549
+ specHash: spec.specHash,
14550
+ file: spec.outFile,
14551
+ fileSha256,
14552
+ lock: entry ? {
14553
+ specHash: entry.specHash,
14554
+ outputSha256,
14555
+ matches: entry.specHash === spec.specHash && outputSha256 !== null && outputSha256 === fileSha256
14556
+ } : null,
14557
+ wouldImport
14558
+ });
14559
+ }
14560
+ return reports;
14561
+ }
14562
+
14563
+ // src/pipeline/adopt.ts
14564
+ import { existsSync as existsSync15 } from "fs";
14565
+ import { readFile as readFile12, writeFile as writeFile8 } from "fs/promises";
14355
14566
  import path18 from "path";
14356
14567
 
14357
14568
  // src/cache.ts
14358
- import { mkdir as mkdir7, readFile as readFile10, rename as rename5, rm as rm5, writeFile as writeFile7 } from "fs/promises";
14359
- import { existsSync as existsSync12 } from "fs";
14569
+ import { mkdir as mkdir7, readFile as readFile11, rename as rename5, rm as rm5, writeFile as writeFile7 } from "fs/promises";
14570
+ import { existsSync as existsSync14 } from "fs";
14360
14571
  import pathModule from "path";
14361
14572
  import { z as z4 } from "zod";
14362
14573
  var HashCacheSchema = z4.object({
@@ -14372,9 +14583,9 @@ function parseCache(value) {
14372
14583
  return HashCacheSchema.parse(value);
14373
14584
  }
14374
14585
  async function loadCache(path53) {
14375
- if (!existsSync12(path53)) return { version: 1, hashes: {} };
14586
+ if (!existsSync14(path53)) return { version: 1, hashes: {} };
14376
14587
  try {
14377
- const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile10(path53, "utf8")));
14588
+ const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile11(path53, "utf8")));
14378
14589
  if (!parsed.success) return { version: 1, hashes: {} };
14379
14590
  return {
14380
14591
  version: 1,
@@ -14431,11 +14642,11 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
14431
14642
  const localByHash = /* @__PURE__ */ new Map();
14432
14643
  const unmatchedLocal = [];
14433
14644
  for (const spec of specs) {
14434
- if (!existsSync13(spec.outFile)) {
14645
+ if (!existsSync15(spec.outFile)) {
14435
14646
  unmatchedLocal.push(`${spec.styleId}/${spec.assetId} (no file at ${spec.outFile})`);
14436
14647
  continue;
14437
14648
  }
14438
- const bytes = await readFile11(spec.outFile);
14649
+ const bytes = await readFile12(spec.outFile);
14439
14650
  try {
14440
14651
  decodePng(bytes);
14441
14652
  } catch (err) {
@@ -14555,7 +14766,7 @@ async function writePromptsBack(manifestPath, lock, opts = {}) {
14555
14766
  const log2 = opts.onProgress ?? (() => {
14556
14767
  });
14557
14768
  const selectedAssets = opts.assetIds ? new Set(opts.assetIds) : null;
14558
- const raw = JSON.parse(await readFile11(manifestPath, "utf8"));
14769
+ const raw = JSON.parse(await readFile12(manifestPath, "utf8"));
14559
14770
  const best = /* @__PURE__ */ new Map();
14560
14771
  for (const entry of Object.values(lock.entries)) {
14561
14772
  if (opts.provider && entry.provider !== opts.provider) continue;
@@ -14588,8 +14799,8 @@ function formatUnmatchedRemote(objects, limit = 15) {
14588
14799
  }
14589
14800
 
14590
14801
  // src/pipeline/adopt-characters.ts
14591
- import { existsSync as existsSync14 } from "fs";
14592
- import { mkdir as mkdir8, readFile as readFile12, writeFile as writeFile9 } from "fs/promises";
14802
+ import { existsSync as existsSync16 } from "fs";
14803
+ import { mkdir as mkdir8, readFile as readFile13, writeFile as writeFile9 } from "fs/promises";
14593
14804
  import path19 from "path";
14594
14805
  async function adoptCharacters(provider, specs, lock, lockPath, opts) {
14595
14806
  const log2 = opts.onProgress ?? (() => {
@@ -14624,8 +14835,8 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
14624
14835
  return bytes;
14625
14836
  };
14626
14837
  const southHash = async (character) => {
14627
- const cached = cache.hashes[`character:${character.id}`];
14628
- if (cached) return cached;
14838
+ const cached2 = cache.hashes[`character:${character.id}`];
14839
+ if (cached2) return cached2;
14629
14840
  if (!character.previewUrl || character.status !== "completed") return null;
14630
14841
  try {
14631
14842
  const hash = sha256(await download(character.previewUrl));
@@ -14641,8 +14852,8 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
14641
14852
  const bytes = await download(source.url);
14642
14853
  const hash = sha256(bytes);
14643
14854
  const file = expectedOutputPath(spec, source.role, index, sources.length);
14644
- if (existsSync14(file)) {
14645
- if (sha256(await readFile12(file)) !== hash) result.differing.push(path19.relative(process.cwd(), file));
14855
+ if (existsSync16(file)) {
14856
+ if (sha256(await readFile13(file)) !== hash) result.differing.push(path19.relative(process.cwd(), file));
14646
14857
  } else {
14647
14858
  await mkdir8(path19.dirname(file), { recursive: true });
14648
14859
  await writeFile9(file, bytes);
@@ -14684,11 +14895,11 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
14684
14895
  if (!match) throw new Error(`remoteId ${spec.remoteId} is not a character on this account`);
14685
14896
  } else {
14686
14897
  const south = expectedOutputPath(spec, "south", 0, spec.character.directions);
14687
- if (!existsSync14(south)) {
14898
+ if (!existsSync16(south)) {
14688
14899
  result.unmatched.push(`${key}: no remoteId and no ${path19.relative(process.cwd(), south)} to match by`);
14689
14900
  return false;
14690
14901
  }
14691
- const localHash = sha256(await readFile12(south));
14902
+ const localHash = sha256(await readFile13(south));
14692
14903
  for (const candidate of remote) {
14693
14904
  if (claimed.has(candidate.id)) continue;
14694
14905
  if (await southHash(candidate) === localHash) {
@@ -14764,7 +14975,7 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
14764
14975
  if (!match) throw new Error(`remoteId ${spec.remoteId} names no ${animation.direction} animation of character ${parentId}`);
14765
14976
  } else {
14766
14977
  const first = expectedOutputPath(spec, "frame-00", 0, 2);
14767
- if (!existsSync14(first)) {
14978
+ if (!existsSync16(first)) {
14768
14979
  const byName = candidates.find((a) => a.name === characterAnimationName(spec));
14769
14980
  if (!byName) {
14770
14981
  result.unmatched.push(`${key}: no remoteId and no ${path19.relative(process.cwd(), first)} to match by`);
@@ -14772,7 +14983,7 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
14772
14983
  }
14773
14984
  match = byName;
14774
14985
  } else {
14775
- const localHash = sha256(await readFile12(first));
14986
+ const localHash = sha256(await readFile13(first));
14776
14987
  for (const candidate of candidates) {
14777
14988
  if (sha256(await download(candidate.frames[0])) === localHash) {
14778
14989
  match = candidate;
@@ -14840,8 +15051,8 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
14840
15051
  }
14841
15052
 
14842
15053
  // src/pipeline/salvage.ts
14843
- import { readFile as readFile13 } from "fs/promises";
14844
- import { existsSync as existsSync15 } from "fs";
15054
+ import { readFile as readFile14 } from "fs/promises";
15055
+ import { existsSync as existsSync17 } from "fs";
14845
15056
  import path20 from "path";
14846
15057
  function providerClaimId(provider, objectId) {
14847
15058
  return `${encodeURIComponent(provider)}:${encodeURIComponent(objectId)}`;
@@ -14849,10 +15060,10 @@ function providerClaimId(provider, objectId) {
14849
15060
  async function loadClaims(lockPaths, opts = {}) {
14850
15061
  const claimed = /* @__PURE__ */ new Set();
14851
15062
  for (const p of lockPaths) {
14852
- if (!existsSync15(p)) throw new Error(`Claim lockfile not found: ${p}`);
15063
+ if (!existsSync17(p)) throw new Error(`Claim lockfile not found: ${p}`);
14853
15064
  let parsed;
14854
15065
  try {
14855
- parsed = parseLock(JSON.parse(await readFile13(p, "utf8")));
15066
+ parsed = parseLock(JSON.parse(await readFile14(p, "utf8")));
14856
15067
  } catch {
14857
15068
  throw new Error(`Claim lockfile is malformed: ${p}`);
14858
15069
  }
@@ -15029,7 +15240,7 @@ async function loadSiblingManifests(ownManifestPath, workspaceManifestPaths, cla
15029
15240
  const siblings = [];
15030
15241
  for (const siblingManifestPath of siblingManifestPaths) {
15031
15242
  if (path20.resolve(siblingManifestPath) === own) continue;
15032
- if (!existsSync15(siblingManifestPath)) continue;
15243
+ if (!existsSync17(siblingManifestPath)) continue;
15033
15244
  try {
15034
15245
  const { manifest } = await loadManifest(siblingManifestPath);
15035
15246
  siblings.push({ label: path20.basename(path20.dirname(siblingManifestPath)), manifest });
@@ -15152,8 +15363,8 @@ async function applyTags(provider, decisions, existing, opts = {}) {
15152
15363
  }
15153
15364
 
15154
15365
  // src/workspace.ts
15155
- import { mkdir as mkdir9, readFile as readFile14, rename as rename6, rm as rm6, writeFile as writeFile10 } from "fs/promises";
15156
- import { existsSync as existsSync16 } from "fs";
15366
+ import { mkdir as mkdir9, readFile as readFile15, rename as rename6, rm as rm6, writeFile as writeFile10 } from "fs/promises";
15367
+ import { existsSync as existsSync18 } from "fs";
15157
15368
  import path21 from "path";
15158
15369
  import { z as z5 } from "zod";
15159
15370
  var WorkspaceProjectSchema = z5.object({
@@ -15179,10 +15390,10 @@ ${parsed.error.issues.slice(0, 5).map((i) => ` ${i.path.join(".")}: ${i.message
15179
15390
  );
15180
15391
  }
15181
15392
  async function loadWorkspace(workspacePath) {
15182
- if (!existsSync16(workspacePath)) return { version: 1, projects: [] };
15393
+ if (!existsSync18(workspacePath)) return { version: 1, projects: [] };
15183
15394
  let raw;
15184
15395
  try {
15185
- raw = JSON.parse(await readFile14(workspacePath, "utf8"));
15396
+ raw = JSON.parse(await readFile15(workspacePath, "utf8"));
15186
15397
  } catch (err) {
15187
15398
  throw new ProjectError(
15188
15399
  `Workspace catalog at ${workspacePath} is malformed:
@@ -15231,14 +15442,14 @@ function validateWorkspace(ws, dir) {
15231
15442
  message: `project "${project.id}" stores an absolute path; the catalog will not resolve correctly if this tree is cloned or moved elsewhere`
15232
15443
  });
15233
15444
  }
15234
- if (!existsSync16(manifestPath)) {
15445
+ if (!existsSync18(manifestPath)) {
15235
15446
  diagnostics.push({
15236
15447
  id: "missing-manifest",
15237
15448
  level: "error",
15238
15449
  message: `project "${project.id}" manifest not found: ${manifestPath}`
15239
15450
  });
15240
15451
  }
15241
- if (!existsSync16(lockPath)) {
15452
+ if (!existsSync18(lockPath)) {
15242
15453
  diagnostics.push({
15243
15454
  id: "missing-lock",
15244
15455
  level: "error",
@@ -15285,7 +15496,7 @@ function validateWorkspace(ws, dir) {
15285
15496
  }
15286
15497
 
15287
15498
  // src/pick/salvage-server.ts
15288
- import { mkdir as mkdir10, writeFile as writeFile11, readFile as readFile16 } from "fs/promises";
15499
+ import { mkdir as mkdir10, writeFile as writeFile11, readFile as readFile17 } from "fs/promises";
15289
15500
  import path22 from "path";
15290
15501
 
15291
15502
  // src/pick/salvage-sheet.ts
@@ -15447,7 +15658,7 @@ refresh();
15447
15658
 
15448
15659
  // src/pick/review-server.ts
15449
15660
  import { createServer } from "http";
15450
- import { readFile as readFile15 } from "fs/promises";
15661
+ import { readFile as readFile16 } from "fs/promises";
15451
15662
 
15452
15663
  // src/open.ts
15453
15664
  import { spawn } from "child_process";
@@ -15474,7 +15685,7 @@ function serveReviewPage(opts) {
15474
15685
  if (req.method === "GET" && req.url && opts.assets?.has(req.url)) {
15475
15686
  try {
15476
15687
  const asset = opts.assets.get(req.url);
15477
- const bytes = await readFile15(asset.path);
15688
+ const bytes = await readFile16(asset.path);
15478
15689
  res.writeHead(200, {
15479
15690
  "Content-Type": asset.contentType,
15480
15691
  "Cache-Control": "no-store",
@@ -15666,7 +15877,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
15666
15877
  }
15667
15878
  }
15668
15879
  await applyTags(provider, decisions, existingTags, { onProgress: log2, characters: characterMembers });
15669
- const raw = JSON.parse(await readFile16(ctx.manifestPath, "utf8"));
15880
+ const raw = JSON.parse(await readFile17(ctx.manifestPath, "utf8"));
15670
15881
  for (const id of importedAssetIds) raw.assets[id] = ctx.manifest.assets[id];
15671
15882
  await writeFile11(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
15672
15883
  await saveLock(ctx.lockPath, ctx.lock);
@@ -15678,7 +15889,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
15678
15889
 
15679
15890
  // src/cli/project.ts
15680
15891
  import path24 from "path";
15681
- import { existsSync as existsSync17 } from "fs";
15892
+ import { existsSync as existsSync19 } from "fs";
15682
15893
 
15683
15894
  // src/project.ts
15684
15895
  import path23 from "path";
@@ -15824,7 +16035,7 @@ async function provenanceFile(id, file) {
15824
16035
  return {
15825
16036
  id,
15826
16037
  path: absolute,
15827
- sha256: existsSync17(absolute) ? await sha256File(absolute) : null,
16038
+ sha256: existsSync19(absolute) ? await sha256File(absolute) : null,
15828
16039
  included: true
15829
16040
  };
15830
16041
  }
@@ -15896,7 +16107,7 @@ function budgetsForPlan(plan, args) {
15896
16107
  return out;
15897
16108
  }
15898
16109
  async function requireCompleteWorkspaceClaims(workspacePath) {
15899
- if (!existsSync17(workspacePath)) {
16110
+ if (!existsSync19(workspacePath)) {
15900
16111
  throw new ProjectError(`Workspace catalog not found: ${workspacePath}`);
15901
16112
  }
15902
16113
  const dir = path24.dirname(path24.resolve(workspacePath));
@@ -15922,7 +16133,7 @@ async function openAccountProject(args) {
15922
16133
  return project;
15923
16134
  }
15924
16135
  async function open(args) {
15925
- if (!existsSync17(path24.resolve(args.manifest))) {
16136
+ if (!existsSync19(path24.resolve(args.manifest))) {
15926
16137
  throw new ProjectError(
15927
16138
  `No manifest at ${path24.resolve(args.manifest)}. Pass --manifest, or run \`pixelkiln init --from <dir>\`.`
15928
16139
  );
@@ -15930,7 +16141,7 @@ async function open(args) {
15930
16141
  const project = await openProject(args.manifest, { lockPath: args.lock, styles: args.styles, assets: args.assets });
15931
16142
  const { loaded, lock } = project;
15932
16143
  let specs = project.specs;
15933
- const accountProvider = ACCOUNT_COMMANDS.has(args.command) ? accountProviderId(loaded.manifest, args.provider, args.command) : void 0;
16144
+ const accountProvider = ACCOUNT_COMMANDS.has(args.command) && !args.local ? accountProviderId(loaded.manifest, args.provider, args.command) : void 0;
15934
16145
  if (args.provider && !accountProvider) {
15935
16146
  throw new UsageError("--provider is only used by balance, adopt, salvage, purge, or workspace add.");
15936
16147
  }
@@ -15976,7 +16187,35 @@ async function runBalance(args) {
15976
16187
  log(` plan: ${b.plan ?? "n/a"}`);
15977
16188
  log(` remaining: ${formatCost(b.unit, b.remaining)}${b.total ? ` of ${b.total}` : ""}`);
15978
16189
  }
16190
+ async function runAdoptLocal(args) {
16191
+ if (args.tag || args.writePrompts) {
16192
+ throw new UsageError("--tag and --write-prompts talk to the account; they cannot be combined with --local.");
16193
+ }
16194
+ const { specs, lock } = await openProject2(args);
16195
+ const result = await importLocal(specs, lock, args.lock, {
16196
+ source: args.source,
16197
+ note: args.note,
16198
+ objectId: args.objectId,
16199
+ force: args.force,
16200
+ dryRun: args.dryRun
16201
+ });
16202
+ if (args.json) {
16203
+ log(JSON.stringify({
16204
+ dryRun: args.dryRun,
16205
+ imported: result.imported.map(({ key, entry }) => ({ key, entry })),
16206
+ skipped: result.skipped
16207
+ }, null, 2));
16208
+ return;
16209
+ }
16210
+ for (const { key, entry } of result.imported) {
16211
+ log(` ${args.dryRun ? "would import" : "imported"} ${key} ${entry.outputs?.[0]?.sha256.slice(0, 12)}`);
16212
+ }
16213
+ for (const { key, reason } of result.skipped) log(` skipped ${key}: ${reason}`);
16214
+ log(`
16215
+ ${result.imported.length} ${args.dryRun ? "to import" : "imported"}, ${result.skipped.length} skipped (offline; no provider contacted)`);
16216
+ }
15979
16217
  async function runAdopt(args) {
16218
+ if (args.local) return runAdoptLocal(args);
15980
16219
  const { loaded, specs, lock, accountProvider } = await openAccountProject(args);
15981
16220
  const providerFor = providerCache("online");
15982
16221
  const provider = providerFor(accountProvider);
@@ -16088,7 +16327,7 @@ async function runSalvage2(args) {
16088
16327
  const lockPaths = [
16089
16328
  .../* @__PURE__ */ new Set([
16090
16329
  ...workspaceLockPaths,
16091
- ...existsSync18(ownLock) ? [ownLock] : [],
16330
+ ...existsSync20(ownLock) ? [ownLock] : [],
16092
16331
  ...args.claims.map((c) => path25.resolve(c))
16093
16332
  ])
16094
16333
  ];
@@ -16350,13 +16589,13 @@ async function runTag(args) {
16350
16589
  import path28 from "path";
16351
16590
 
16352
16591
  // src/pipeline/hand-edit.ts
16353
- import { existsSync as existsSync19 } from "fs";
16354
- import { copyFile, mkdir as mkdir11, readFile as readFile18, rename as rename8, rm as rm8, writeFile as writeFile13 } from "fs/promises";
16592
+ import { existsSync as existsSync21 } from "fs";
16593
+ import { copyFile, mkdir as mkdir11, readFile as readFile19, rename as rename8, rm as rm8, writeFile as writeFile13 } from "fs/promises";
16355
16594
  import path27 from "path";
16356
16595
  import { z as z7 } from "zod";
16357
16596
 
16358
16597
  // src/manifest-edit.ts
16359
- import { readFile as readFile17, rename as rename7, rm as rm7, writeFile as writeFile12 } from "fs/promises";
16598
+ import { readFile as readFile18, rename as rename7, rm as rm7, writeFile as writeFile12 } from "fs/promises";
16360
16599
  import path26 from "path";
16361
16600
  import { z as z6 } from "zod";
16362
16601
  var HexSha = z6.string().regex(/^[0-9a-f]{64}$/);
@@ -16781,7 +17020,7 @@ function applyEdit(raw, edit) {
16781
17020
  }
16782
17021
  async function withCandidate(manifestPath, edit, use, unchanged) {
16783
17022
  const absolute = path26.resolve(manifestPath);
16784
- const original = await readFile17(absolute, "utf8");
17023
+ const original = await readFile18(absolute, "utf8");
16785
17024
  if (sha256(original) !== edit.expectedSha256) throw new ManifestDriftError(absolute);
16786
17025
  let raw;
16787
17026
  try {
@@ -16886,10 +17125,10 @@ function handEditBases(spec, lock) {
16886
17125
  }));
16887
17126
  if (members.some((member) => member.mediaType && member.mediaType !== "image/png")) return null;
16888
17127
  if (entry.outputs.length === 1 && !primaryOutput(entry)) return null;
16889
- if (!members.every((member) => existsSync19(member.path))) return null;
17128
+ if (!members.every((member) => existsSync21(member.path))) return null;
16890
17129
  return members.map(({ role, path: file }) => ({ role, path: file }));
16891
17130
  }
16892
- return existsSync19(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
17131
+ return existsSync21(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
16893
17132
  }
16894
17133
  function handEditMembers(loaded, spec, lock, editPath) {
16895
17134
  const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
@@ -16920,7 +17159,7 @@ async function startHandEdit(loaded, lock, spec, opts = {}) {
16920
17159
  const members = handEditMembers(loaded, spec, lock, editPath);
16921
17160
  let created = false;
16922
17161
  for (const member of members) {
16923
- if (existsSync19(member.path)) continue;
17162
+ if (existsSync21(member.path)) continue;
16924
17163
  if (!member.base) {
16925
17164
  throw new ManifestEditError(
16926
17165
  `${spec.styleId}/${spec.assetId} has no generated PNG on disk to start from; generate or restore it first`
@@ -17005,7 +17244,7 @@ function handEditProjectPath(editPath) {
17005
17244
  async function readHandEditCompanion(editPath) {
17006
17245
  let text;
17007
17246
  try {
17008
- text = await readFile18(handEditCompanionPath(editPath), "utf8");
17247
+ text = await readFile19(handEditCompanionPath(editPath), "utf8");
17009
17248
  } catch {
17010
17249
  return null;
17011
17250
  }
@@ -17048,7 +17287,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
17048
17287
  }
17049
17288
  });
17050
17289
  const bases = handEditBases(spec, lock);
17051
- const expectedSize = bases?.[0] ? decodePng(await readFile18(bases[0].path)) : { width: spec.width, height: spec.height };
17290
+ const expectedSize = bases?.[0] ? decodePng(await readFile19(bases[0].path)) : { width: spec.width, height: spec.height };
17052
17291
  for (const [index, image] of decoded.entries()) {
17053
17292
  if (image.width !== expectedSize.width || image.height !== expectedSize.height) {
17054
17293
  const which = memberSet ? `member ${incoming[index].role ?? index}` : "the edit";
@@ -17135,21 +17374,21 @@ async function runEdit(args) {
17135
17374
 
17136
17375
  // src/cli/commands/gallery.ts
17137
17376
  import path38 from "path";
17138
- import { existsSync as existsSync29 } from "fs";
17377
+ import { existsSync as existsSync31 } from "fs";
17139
17378
 
17140
17379
  // src/gallery/snapshot.ts
17141
17380
  import { createHash as createHash4 } from "crypto";
17142
- import { existsSync as existsSync24 } from "fs";
17143
- import { readFile as readFile22, stat as stat2 } from "fs/promises";
17381
+ import { existsSync as existsSync26 } from "fs";
17382
+ import { readFile as readFile23, stat as stat2 } from "fs/promises";
17144
17383
  import path34 from "path";
17145
17384
 
17146
17385
  // src/gallery/edit.ts
17147
- import { readFile as readFile21, rename as rename9, writeFile as writeFile17 } from "fs/promises";
17386
+ import { readFile as readFile22, rename as rename9, writeFile as writeFile17 } from "fs/promises";
17148
17387
  import path32 from "path";
17149
17388
  import { z as z11 } from "zod";
17150
17389
 
17151
17390
  // src/gallery/upload.ts
17152
- import { existsSync as existsSync20 } from "fs";
17391
+ import { existsSync as existsSync22 } from "fs";
17153
17392
  import { mkdir as mkdir12, writeFile as writeFile14 } from "fs/promises";
17154
17393
  import path29 from "path";
17155
17394
  import { z as z8 } from "zod";
@@ -17181,7 +17420,7 @@ async function saveProjectImage(root, request) {
17181
17420
  if (metadata.format !== expected) {
17182
17421
  throw new ManifestEditError(`the upload is a ${metadata.format.toUpperCase()}; name it ${metadata.format === "png" ? ".png" : ".jpg"}`);
17183
17422
  }
17184
- if (existsSync20(file) && !request.overwrite) {
17423
+ if (existsSync22(file) && !request.overwrite) {
17185
17424
  throw new ManifestEditError(`${relative.split(path29.sep).join("/")} already exists; choose another name, or replace it`);
17186
17425
  }
17187
17426
  await mkdir12(path29.dirname(file), { recursive: true });
@@ -17190,8 +17429,8 @@ async function saveProjectImage(root, request) {
17190
17429
  }
17191
17430
 
17192
17431
  // src/gallery/image-revision.ts
17193
- import { existsSync as existsSync21 } from "fs";
17194
- import { readFile as readFile19, rm as rm9, writeFile as writeFile15 } from "fs/promises";
17432
+ import { existsSync as existsSync23 } from "fs";
17433
+ import { readFile as readFile20, rm as rm9, writeFile as writeFile15 } from "fs/promises";
17195
17434
  import path30 from "path";
17196
17435
  import { z as z9 } from "zod";
17197
17436
  var InpaintRevisionRequestSchema = z9.object({
@@ -17219,7 +17458,7 @@ async function createInpaintRevision(manifestPath, request) {
17219
17458
  const metadata = imageMetadata(bytes);
17220
17459
  if (!metadata || metadata.format !== "png") throw new ManifestEditError("the mask is not a readable PNG");
17221
17460
  const file = path30.resolve(root, request.maskPath);
17222
- const previous = existsSync21(file) ? await readFile19(file) : null;
17461
+ const previous = existsSync23(file) ? await readFile20(file) : null;
17223
17462
  const mask = await saveProjectImage(root, {
17224
17463
  action: "upload-image",
17225
17464
  path: request.maskPath,
@@ -17246,8 +17485,8 @@ async function createInpaintRevision(manifestPath, request) {
17246
17485
  }
17247
17486
 
17248
17487
  // src/gallery/skeleton.ts
17249
- import { existsSync as existsSync22 } from "fs";
17250
- import { mkdir as mkdir13, readFile as readFile20, rm as rm10, writeFile as writeFile16 } from "fs/promises";
17488
+ import { existsSync as existsSync24 } from "fs";
17489
+ import { mkdir as mkdir13, readFile as readFile21, rm as rm10, writeFile as writeFile16 } from "fs/promises";
17251
17490
  import path31 from "path";
17252
17491
  import { z as z10 } from "zod";
17253
17492
  var SkeletonEstimateRequestSchema = z10.object({
@@ -17289,7 +17528,7 @@ var SkeletonKeypointsUpdateSchema = z10.object({
17289
17528
  var DEFAULT_ESTIMATE_LIMIT = 10;
17290
17529
  function skeletonSourceFile(spec) {
17291
17530
  if (spec.source) return path31.resolve(spec.root, spec.source);
17292
- if (spec.quality && existsSync22(spec.quality.outFile)) return spec.quality.outFile;
17531
+ if (spec.quality && existsSync24(spec.quality.outFile)) return spec.quality.outFile;
17293
17532
  return spec.outFile;
17294
17533
  }
17295
17534
  function createGallerySkeletonHandlers(opts) {
@@ -17310,8 +17549,8 @@ function createGallerySkeletonHandlers(opts) {
17310
17549
  const spec = ctx.specs.find((candidate) => lockKey(candidate.styleId, candidate.assetId) === key);
17311
17550
  if (!spec) throw new ManifestEditError(`"${key}" is not declared by the manifest`);
17312
17551
  const file = skeletonSourceFile(spec);
17313
- if (!existsSync22(file)) throw new ManifestEditError(`${key} has no image on disk to estimate from`);
17314
- const bytes = await readFile20(file);
17552
+ if (!existsSync24(file)) throw new ManifestEditError(`${key} has no image on disk to estimate from`);
17553
+ const bytes = await readFile21(file);
17315
17554
  const metadata = imageMetadata(bytes);
17316
17555
  if (!metadata) throw new ManifestEditError(`${path31.basename(file)} is not a readable PNG or JPEG`);
17317
17556
  const problem = estimateSkeletonSizeProblem(metadata.width, metadata.height);
@@ -17350,13 +17589,13 @@ async function createSkeletonAnimation(manifestPath, request) {
17350
17589
  if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || path31.isAbsolute(relative)) {
17351
17590
  throw new ManifestEditError("the keypoints file must be a .json path inside the project");
17352
17591
  }
17353
- const existed = existsSync22(file);
17592
+ const existed = existsSync24(file);
17354
17593
  let previous = null;
17355
17594
  if (request.set) {
17356
17595
  if (existed && !request.overwrite) {
17357
17596
  throw new ManifestEditError(`${request.keypointsFile} already exists; choose another path, or replace it`);
17358
17597
  }
17359
- if (existed) previous = await readFile20(file);
17598
+ if (existed) previous = await readFile21(file);
17360
17599
  await mkdir13(path31.dirname(file), { recursive: true });
17361
17600
  await writeFile16(file, JSON.stringify(request.set, null, 2) + "\n");
17362
17601
  } else if (!existed) {
@@ -17398,7 +17637,7 @@ async function updateSkeletonKeypoints(ctx, request) {
17398
17637
  if (relative.startsWith("..") || path31.isAbsolute(relative)) {
17399
17638
  throw new ManifestEditError(`${key}'s keypoints file is outside the project; edit it by hand`);
17400
17639
  }
17401
- const current = existsSync22(file) ? sha256(await readFile20(file)) : null;
17640
+ const current = existsSync24(file) ? sha256(await readFile21(file)) : null;
17402
17641
  if (current !== request.expectedSha256) {
17403
17642
  throw Object.assign(
17404
17643
  new Error(`${relative.split(path31.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
@@ -17470,7 +17709,7 @@ function createGalleryEditHandler(opts) {
17470
17709
  if (undo.success) {
17471
17710
  const manifestPath2 = await manifestOf(undo.data.project);
17472
17711
  if (!manifestPath2) throw new ManifestEditError("no manifest to undo an edit in");
17473
- const current = await readFile21(manifestPath2, "utf8");
17712
+ const current = await readFile22(manifestPath2, "utf8");
17474
17713
  if (sha256(current) !== undo.data.expectedSha256) throw new ManifestDriftError(manifestPath2);
17475
17714
  const stack = history.get(manifestPath2) ?? [];
17476
17715
  const last = stack[stack.length - 1];
@@ -17487,10 +17726,10 @@ function createGalleryEditHandler(opts) {
17487
17726
  return opts.reload();
17488
17727
  }
17489
17728
  const manifestPath = await manifestOf(body?.project);
17490
- const before = manifestPath ? await readFile21(manifestPath, "utf8").catch(() => null) : null;
17729
+ const before = manifestPath ? await readFile22(manifestPath, "utf8").catch(() => null) : null;
17491
17730
  const build = await apply(body);
17492
17731
  if (manifestPath && before !== null) {
17493
- const after = await readFile21(manifestPath, "utf8").catch(() => null);
17732
+ const after = await readFile22(manifestPath, "utf8").catch(() => null);
17494
17733
  if (after !== null && after !== before) {
17495
17734
  const stack = history.get(manifestPath) ?? [];
17496
17735
  stack.push({ before, afterSha: sha256(after) });
@@ -17663,7 +17902,7 @@ function createGalleryPriceHandler(opts) {
17663
17902
  }
17664
17903
 
17665
17904
  // src/pipeline/history.ts
17666
- import { existsSync as existsSync23 } from "fs";
17905
+ import { existsSync as existsSync25 } from "fs";
17667
17906
  import path33 from "path";
17668
17907
  var HISTORY_ENV = "PIXELKILN_HISTORY";
17669
17908
  function historyLimit(manifest, env = process.env) {
@@ -17754,7 +17993,7 @@ async function revertGeneration(provider, spec, lock, lockPath, opts) {
17754
17993
  }
17755
17994
  for (let i = 0; i < entry.outputs.length; i++) {
17756
17995
  const file = currentEntryOutputPath(entry, spec, i);
17757
- if (!existsSync23(file)) continue;
17996
+ if (!existsSync25(file)) continue;
17758
17997
  if (await sha256File(file) !== entry.outputs[i].sha256 && !opts.force) {
17759
17998
  throw new OverwriteRefusedError(
17760
17999
  `${path33.relative(process.cwd(), file)} was changed after download; keep it with pixelkiln edit, or pass --force to replace it`,
@@ -17844,7 +18083,7 @@ function describeHistory(media, entry, cacheDir) {
17844
18083
  const mediaType = output.mediaType ?? MediaType.PNG;
17845
18084
  const file = path34.join(cacheDir, cacheFileName(output.sha256, mediaType));
17846
18085
  let url = null;
17847
- if (existsSync24(file)) {
18086
+ if (existsSync26(file)) {
17848
18087
  const id = galleryMediaId(file);
17849
18088
  media.set(id, { path: file, contentType: mediaType });
17850
18089
  url = `${galleryMediaRoute(id)}?v=${output.sha256.slice(0, 24)}`;
@@ -17876,7 +18115,7 @@ function describeHistory(media, entry, cacheDir) {
17876
18115
  var MAX_COMPARED_BYTES = 8 * 1024 * 1024;
17877
18116
  async function samePixels(a, b) {
17878
18117
  try {
17879
- const [left, right] = await Promise.all([readFile22(a), readFile22(b)]);
18118
+ const [left, right] = await Promise.all([readFile23(a), readFile23(b)]);
17880
18119
  if (left.length > MAX_COMPARED_BYTES || right.length > MAX_COMPARED_BYTES) return false;
17881
18120
  const x = decodePng(left);
17882
18121
  const y = decodePng(right);
@@ -17977,7 +18216,7 @@ async function describeQuality(media, root, inspection) {
17977
18216
  outputPaths.map((file) => describeOutput(media, root, path34.resolve(root, file)))
17978
18217
  );
17979
18218
  const recordPath = path34.resolve(root, inspection.record);
17980
- const recordExists = existsSync24(recordPath);
18219
+ const recordExists = existsSync26(recordPath);
17981
18220
  let options = null;
17982
18221
  let check = null;
17983
18222
  if (recordExists) {
@@ -18034,7 +18273,7 @@ async function buildGallerySnapshot(opts) {
18034
18273
  const media = /* @__PURE__ */ new Map();
18035
18274
  const plan = await buildPlan(specs, lock);
18036
18275
  const items = [];
18037
- const manifestText = await readFile22(loaded.path, "utf8");
18276
+ const manifestText = await readFile23(loaded.path, "utf8");
18038
18277
  const manifestSha256 = sha256(manifestText);
18039
18278
  const cacheDir = path34.resolve(path34.dirname(opts.lockPath), ".pixelkiln", "cache");
18040
18279
  let rawStyles = {};
@@ -18065,7 +18304,7 @@ async function buildGallerySnapshot(opts) {
18065
18304
  const editShas = await Promise.all(
18066
18305
  Array.from({ length: memberCount }, async (_, index) => {
18067
18306
  const file = sourceOutputPath(spec.source, entry, index, root);
18068
- return { file, sha256: existsSync24(file) ? await sha256File(file) : null };
18307
+ return { file, sha256: existsSync26(file) ? await sha256File(file) : null };
18069
18308
  })
18070
18309
  );
18071
18310
  edits = await Promise.all(editShas.map(({ file, sha256: editSha }) => describeOutput(media, root, file, { sha256: editSha })));
@@ -18073,7 +18312,7 @@ async function buildGallerySnapshot(opts) {
18073
18312
  const companion = await readHandEditCompanion(editPath);
18074
18313
  if (companion) {
18075
18314
  const projectPath = handEditProjectPath(editPath);
18076
- const project = companion.project && existsSync24(projectPath) ? await fileInfo(projectPath) : null;
18315
+ const project = companion.project && existsSync26(projectPath) ? await fileInfo(projectPath) : null;
18077
18316
  let projectUrl = null;
18078
18317
  if (project) {
18079
18318
  const id = galleryMediaId(projectPath);
@@ -18110,7 +18349,7 @@ async function buildGallerySnapshot(opts) {
18110
18349
  }
18111
18350
  } else if (spec.source) {
18112
18351
  outputs = [await describeOutput(media, root, path34.resolve(root, spec.source))];
18113
- } else if (!entry && existsSync24(spec.outFile)) {
18352
+ } else if (!entry && existsSync26(spec.outFile)) {
18114
18353
  outputs = [await describeOutput(media, root, spec.outFile)];
18115
18354
  } else {
18116
18355
  outputs = [];
@@ -18387,7 +18626,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
18387
18626
  root: loaded.root,
18388
18627
  provider: loaded.manifest.provider,
18389
18628
  account: project.account ?? null,
18390
- manifestSha256: manifestSha256 ?? sha256(await readFile22(manifestPath, "utf8")),
18629
+ manifestSha256: manifestSha256 ?? sha256(await readFile23(manifestPath, "utf8")),
18391
18630
  historyLimit: historyLimit(loaded.manifest),
18392
18631
  entries: Object.keys(lock.entries).length,
18393
18632
  items: projectItems.length,
@@ -18446,10 +18685,10 @@ async function buildWorkspaceGallerySnapshot(opts) {
18446
18685
  // src/gallery/server.ts
18447
18686
  import { randomBytes } from "crypto";
18448
18687
  import { createServer as createServer2 } from "http";
18449
- import { readFile as readFile23 } from "fs/promises";
18688
+ import { readFile as readFile24 } from "fs/promises";
18450
18689
 
18451
18690
  // src/gallery/page.ts
18452
- import { existsSync as existsSync25, readFileSync as readFileSync5 } from "fs";
18691
+ import { existsSync as existsSync27, readFileSync as readFileSync6 } from "fs";
18453
18692
 
18454
18693
  // src/gallery/client-bundle.ts
18455
18694
  import { createRequire } from "module";
@@ -18489,8 +18728,8 @@ var client;
18489
18728
  function clientAssets() {
18490
18729
  const prebuilt = new URL("gallery.js", CLIENT_DIR);
18491
18730
  client ??= {
18492
- css: readFileSync5(new URL("gallery.css", CLIENT_DIR), "utf8"),
18493
- js: existsSync25(prebuilt) ? readFileSync5(prebuilt, "utf8") : bundleGalleryClient()
18731
+ css: readFileSync6(new URL("gallery.css", CLIENT_DIR), "utf8"),
18732
+ js: existsSync27(prebuilt) ? readFileSync6(prebuilt, "utf8") : bundleGalleryClient()
18494
18733
  };
18495
18734
  return client;
18496
18735
  }
@@ -18761,7 +19000,7 @@ async function serveGallery(opts) {
18761
19000
  const asset = reviewAssets.get(jobId)?.get(url2.pathname);
18762
19001
  if (!asset) return fail(404, "no such review asset");
18763
19002
  try {
18764
- const bytes = await readFile23(asset.path);
19003
+ const bytes = await readFile24(asset.path);
18765
19004
  res.writeHead(200, {
18766
19005
  "Content-Type": asset.contentType,
18767
19006
  "Cache-Control": "no-store",
@@ -18844,7 +19083,7 @@ async function serveGallery(opts) {
18844
19083
  if (!asset) return fail(404, "no such gallery media");
18845
19084
  let bytes;
18846
19085
  try {
18847
- bytes = await readFile23(asset.path);
19086
+ bytes = await readFile24(asset.path);
18848
19087
  } catch {
18849
19088
  return fail(404, "gallery media is no longer on disk; refresh the page");
18850
19089
  }
@@ -19337,12 +19576,12 @@ function ownedReferenceImageId(spec, lock, providerId) {
19337
19576
  }
19338
19577
 
19339
19578
  // src/pick/server.ts
19340
- import { existsSync as existsSync27 } from "fs";
19341
- import { readFile as readFile25 } from "fs/promises";
19579
+ import { existsSync as existsSync29 } from "fs";
19580
+ import { readFile as readFile26 } from "fs/promises";
19342
19581
 
19343
19582
  // src/pipeline/init.ts
19344
- import { readdir, readFile as readFile24, writeFile as writeFile18 } from "fs/promises";
19345
- import { existsSync as existsSync26 } from "fs";
19583
+ import { readdir, readFile as readFile25, writeFile as writeFile18 } from "fs/promises";
19584
+ import { existsSync as existsSync28 } from "fs";
19346
19585
  import path35 from "path";
19347
19586
  function pngSize(buf) {
19348
19587
  if (buf.length < 24) return null;
@@ -19371,7 +19610,7 @@ async function scanAssets(root, opts = {}) {
19371
19610
  const skipped = [];
19372
19611
  const seen = /* @__PURE__ */ new Map();
19373
19612
  for (const file of files.sort()) {
19374
- const size = pngSize(await readFile24(file));
19613
+ const size = pngSize(await readFile25(file));
19375
19614
  if (!size) {
19376
19615
  skipped.push(`${file} (not a readable PNG)`);
19377
19616
  continue;
@@ -19436,7 +19675,7 @@ function mode(values) {
19436
19675
  return [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? 64;
19437
19676
  }
19438
19677
  async function writeManifestFile(target, manifest) {
19439
- if (existsSync26(target)) {
19678
+ if (existsSync28(target)) {
19440
19679
  throw new Error(`${target} already exists; refusing to overwrite an existing manifest.`);
19441
19680
  }
19442
19681
  await writeFile18(target, JSON.stringify(manifest, null, 2) + "\n");
@@ -19862,13 +20101,13 @@ async function currentArt(entry, spec) {
19862
20101
  const previous = primaryOutput({ ...entry, outputs: entry.supersededOutputs });
19863
20102
  if (!previous) return null;
19864
20103
  const file = resolveOutputPath(previous.path, spec.root);
19865
- if (!existsSync27(file)) return null;
20104
+ if (!existsSync29(file)) return null;
19866
20105
  const contentType = previous.mediaType ?? mediaTypeFromExtension(file);
19867
20106
  if (!contentType) return null;
19868
20107
  let width = entry.width;
19869
20108
  let height = entry.height;
19870
20109
  if (contentType === "image/png") {
19871
- const size = pngSize(await readFile25(file));
20110
+ const size = pngSize(await readFile26(file));
19872
20111
  if (size) ({ width, height } = size);
19873
20112
  }
19874
20113
  return { path: file, contentType, width, height };
@@ -19876,7 +20115,7 @@ async function currentArt(entry, spec) {
19876
20115
  async function cachedFrame(url) {
19877
20116
  if (!url.startsWith("file://")) return null;
19878
20117
  const file = url.slice("file://".length);
19879
- const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await readFile25(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
20118
+ const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await readFile26(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
19880
20119
  return { path: file, contentType };
19881
20120
  }
19882
20121
  async function prepareReview(provider, lock, opts = {}) {
@@ -19902,15 +20141,15 @@ async function prepareReview(provider, lock, opts = {}) {
19902
20141
  const frameAssets = [];
19903
20142
  const frameSizes = [];
19904
20143
  for (const [index, url] of urls.entries()) {
19905
- const cached = await cachedFrame(url);
19906
- if (!cached) {
20144
+ const cached2 = await cachedFrame(url);
20145
+ if (!cached2) {
19907
20146
  frameUrls.push(url);
19908
20147
  frameSizes.push(null);
19909
20148
  continue;
19910
20149
  }
19911
- frameSizes.push(cached.contentType === "image/png" ? pngSize(await readFile25(cached.path).catch(() => Buffer.alloc(0))) : null);
20150
+ frameSizes.push(cached2.contentType === "image/png" ? pngSize(await readFile26(cached2.path).catch(() => Buffer.alloc(0))) : null);
19912
20151
  const route = `${prefix}/review-frame/${encodeURIComponent(String(groups.length))}/${index}`;
19913
- frameAssets.push([route, cached]);
20152
+ frameAssets.push([route, cached2]);
19914
20153
  frameUrls.push(route);
19915
20154
  }
19916
20155
  const sourceRoute = spec?.revision ? `${prefix}/revision-source/${encodeURIComponent(String(groups.length))}` : null;
@@ -20426,13 +20665,13 @@ function createGenerateHandlers(opts) {
20426
20665
  }
20427
20666
 
20428
20667
  // src/gallery/editor.ts
20429
- import { readFile as readFile27 } from "fs/promises";
20668
+ import { readFile as readFile28 } from "fs/promises";
20430
20669
  import path37 from "path";
20431
20670
 
20432
20671
  // src/editor/install.ts
20433
20672
  import { createHash as createHash5 } from "crypto";
20434
- import { existsSync as existsSync28 } from "fs";
20435
- import { mkdir as mkdir14, readFile as readFile26, rename as rename10, rm as rm11, stat as stat3, writeFile as writeFile19 } from "fs/promises";
20673
+ import { existsSync as existsSync30 } from "fs";
20674
+ import { mkdir as mkdir14, readFile as readFile27, rename as rename10, rm as rm11, stat as stat3, writeFile as writeFile19 } from "fs/promises";
20436
20675
  import os3 from "os";
20437
20676
  import path36 from "path";
20438
20677
 
@@ -20516,7 +20755,7 @@ function editorBaseUrl(pin = EDITOR_PIN) {
20516
20755
  }
20517
20756
  async function sha256Of(file) {
20518
20757
  try {
20519
- return createHash5("sha256").update(await readFile26(file)).digest("hex");
20758
+ return createHash5("sha256").update(await readFile27(file)).digest("hex");
20520
20759
  } catch {
20521
20760
  return null;
20522
20761
  }
@@ -20530,7 +20769,7 @@ async function editorStatus(opts = {}) {
20530
20769
  for (const [name, expected] of Object.entries(pin.files)) {
20531
20770
  totalBytes += expected.bytes;
20532
20771
  const file = path36.join(dir, name);
20533
- const info = existsSync28(file) ? await stat3(file).catch(() => null) : null;
20772
+ const info = existsSync30(file) ? await stat3(file).catch(() => null) : null;
20534
20773
  if (info && info.size === expected.bytes && await sha256Of(file) === expected.sha256) {
20535
20774
  installedBytes += expected.bytes;
20536
20775
  } else {
@@ -20709,7 +20948,7 @@ function createGalleryEditorHandlers(opts = {}) {
20709
20948
  if (!status.installed) return null;
20710
20949
  let bytes;
20711
20950
  try {
20712
- bytes = await readFile27(path37.join(dir, name));
20951
+ bytes = await readFile28(path37.join(dir, name));
20713
20952
  } catch {
20714
20953
  verified = null;
20715
20954
  return null;
@@ -20818,7 +21057,7 @@ async function serveUntilStopped(initial, reload, args, access2) {
20818
21057
  async function runGallery(args) {
20819
21058
  if (args.workspace) {
20820
21059
  const workspacePath = path38.resolve(args.workspace);
20821
- if (!existsSync29(workspacePath)) {
21060
+ if (!existsSync31(workspacePath)) {
20822
21061
  throw new Error(`Workspace catalog not found: ${workspacePath}`);
20823
21062
  }
20824
21063
  const filter2 = { styles: args.styles, assets: args.assets };
@@ -21172,14 +21411,14 @@ async function runRestoreGeneration(args) {
21172
21411
  }
21173
21412
 
21174
21413
  // src/cli/commands/housekeeping.ts
21175
- import { existsSync as existsSync31 } from "fs";
21414
+ import { existsSync as existsSync33 } from "fs";
21176
21415
 
21177
21416
  // src/pipeline/cache-health.ts
21178
- import { existsSync as existsSync30 } from "fs";
21179
- import { readFile as readFile28, readdir as readdir2, rm as rm12 } from "fs/promises";
21417
+ import { existsSync as existsSync32 } from "fs";
21418
+ import { readFile as readFile29, readdir as readdir2, rm as rm12 } from "fs/promises";
21180
21419
  import path39 from "path";
21181
21420
  async function inspectCaches(lock, lockPath, options = {}) {
21182
- if (options.prune && !existsSync30(lockPath)) {
21421
+ if (options.prune && !existsSync32(lockPath)) {
21183
21422
  throw new Error(`Refusing to prune without an existing lockfile at ${path39.resolve(lockPath)}`);
21184
21423
  }
21185
21424
  const contentDir = path39.resolve(path39.dirname(lockPath), ".pixelkiln", "cache");
@@ -21204,7 +21443,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
21204
21443
  await saveCache(remotePath, { version: 1, hashes: {} });
21205
21444
  removed.resetRemoteHashCache = true;
21206
21445
  } else if (remoteHashes.invalidIds.length) {
21207
- const cache = parseCache(JSON.parse(await readFile28(remotePath, "utf8")));
21446
+ const cache = parseCache(JSON.parse(await readFile29(remotePath, "utf8")));
21208
21447
  for (const id of remoteHashes.invalidIds) delete cache.hashes[id];
21209
21448
  removed.remoteHashEntries = remoteHashes.invalidIds.length;
21210
21449
  await saveCache(remotePath, cache);
@@ -21222,7 +21461,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
21222
21461
  async function inspectContentCache(contentDir, referenced) {
21223
21462
  const report = {
21224
21463
  path: contentDir,
21225
- exists: existsSync30(contentDir),
21464
+ exists: existsSync32(contentDir),
21226
21465
  files: 0,
21227
21466
  bytes: 0,
21228
21467
  valid: 0,
@@ -21248,7 +21487,7 @@ async function inspectContentCache(contentDir, referenced) {
21248
21487
  const expected = mediaType ? entry.name.slice(0, -4) : "";
21249
21488
  let bytes;
21250
21489
  try {
21251
- bytes = await readFile28(file);
21490
+ bytes = await readFile29(file);
21252
21491
  report.bytes += bytes.length;
21253
21492
  } catch (err) {
21254
21493
  report.invalid.push({
@@ -21286,7 +21525,7 @@ async function inspectContentCache(contentDir, referenced) {
21286
21525
  async function inspectRemoteHashCache(remotePath) {
21287
21526
  const report = {
21288
21527
  path: remotePath,
21289
- exists: existsSync30(remotePath),
21528
+ exists: existsSync32(remotePath),
21290
21529
  entries: 0,
21291
21530
  valid: 0,
21292
21531
  invalidIds: [],
@@ -21295,7 +21534,7 @@ async function inspectRemoteHashCache(remotePath) {
21295
21534
  if (!report.exists) return report;
21296
21535
  let cache;
21297
21536
  try {
21298
- cache = parseCache(JSON.parse(await readFile28(remotePath, "utf8")));
21537
+ cache = parseCache(JSON.parse(await readFile29(remotePath, "utf8")));
21299
21538
  } catch (err) {
21300
21539
  report.error = err instanceof Error ? err.message : String(err);
21301
21540
  return report;
@@ -21359,7 +21598,7 @@ async function runAccept(args) {
21359
21598
  let intact = true;
21360
21599
  for (const output of entry.outputs) {
21361
21600
  const file = resolveOutputPath(output.path, item.spec.root);
21362
- if (!existsSync31(file) || await sha256File(file) !== output.sha256) {
21601
+ if (!existsSync33(file) || await sha256File(file) !== output.sha256) {
21363
21602
  intact = false;
21364
21603
  break;
21365
21604
  }
@@ -21415,11 +21654,11 @@ This drops their provenance from the lockfile. The art on disk is`);
21415
21654
 
21416
21655
  // src/cli/commands/init.ts
21417
21656
  import path40 from "path";
21418
- import { existsSync as existsSync32 } from "fs";
21657
+ import { existsSync as existsSync34 } from "fs";
21419
21658
  async function runInit(args) {
21420
21659
  if (!args.from) throw new Error("init needs --from <dir> pointing at your existing PNGs.");
21421
21660
  const root = path40.resolve(args.from);
21422
- if (!existsSync32(root)) throw new Error(`No directory at ${root}`);
21661
+ if (!existsSync34(root)) throw new Error(`No directory at ${root}`);
21423
21662
  const generator = args.generator ?? "map";
21424
21663
  if (generator !== "1dir" && generator !== "map") {
21425
21664
  throw new Error(`--generator must be "1dir" or "map", got "${args.generator}".`);
@@ -21447,7 +21686,7 @@ async function runInit(args) {
21447
21686
  }
21448
21687
 
21449
21688
  // src/pipeline/doctor.ts
21450
- import { constants, existsSync as existsSync33 } from "fs";
21689
+ import { constants, existsSync as existsSync35 } from "fs";
21451
21690
  import { access, stat as stat4 } from "fs/promises";
21452
21691
  import path41 from "path";
21453
21692
  async function doctor(loaded, specs, lock, lockPath, opts = {}) {
@@ -21515,11 +21754,11 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
21515
21754
  const hasSource = Boolean(entry.sourceUrl || entry.sourceUrls?.length);
21516
21755
  let hasCache = false;
21517
21756
  for (const output of entry.outputs) {
21518
- const cached = path41.join(
21757
+ const cached2 = path41.join(
21519
21758
  cacheDir,
21520
21759
  cacheFileName(output.sha256, output.mediaType ?? MediaType.PNG)
21521
21760
  );
21522
- if (existsSync33(cached) && await sha256File(cached) === output.sha256) {
21761
+ if (existsSync35(cached2) && await sha256File(cached2) === output.sha256) {
21523
21762
  hasCache = true;
21524
21763
  break;
21525
21764
  }
@@ -21622,8 +21861,8 @@ async function nearestExistingDirectory(start) {
21622
21861
  }
21623
21862
 
21624
21863
  // src/pipeline/audit.ts
21625
- import { readFile as readFile29 } from "fs/promises";
21626
- import { existsSync as existsSync34 } from "fs";
21864
+ import { readFile as readFile30 } from "fs/promises";
21865
+ import { existsSync as existsSync36 } from "fs";
21627
21866
  import path42 from "path";
21628
21867
  function paletteDistance(asset, reference) {
21629
21868
  if (!asset.length || !reference.length) return 0;
@@ -21660,12 +21899,12 @@ async function auditStyle(loaded, specs, styleId, lock) {
21660
21899
  const unreadable = [];
21661
21900
  for (const spec of mine) {
21662
21901
  for (const output of resolveSpecOutputs(spec, lock, loaded.root)) {
21663
- if (!existsSync34(output.absolutePath)) {
21902
+ if (!existsSync36(output.absolutePath)) {
21664
21903
  missing.push(output.id);
21665
21904
  continue;
21666
21905
  }
21667
21906
  try {
21668
- const png = decodePng(await readFile29(output.absolutePath));
21907
+ const png = decodePng(await readFile30(output.absolutePath));
21669
21908
  const palette = extractPalette(png, 12);
21670
21909
  assets.push({
21671
21910
  assetId: spec.assetId,
@@ -21690,9 +21929,9 @@ async function auditStyle(loaded, specs, styleId, lock) {
21690
21929
  const refPalettes = [];
21691
21930
  for (const img of style.styleImages) {
21692
21931
  const abs = path42.resolve(loaded.root, img.path);
21693
- if (!existsSync34(abs)) continue;
21932
+ if (!existsSync36(abs)) continue;
21694
21933
  try {
21695
- refPalettes.push(extractPalette(decodePng(await readFile29(abs)), 12));
21934
+ refPalettes.push(extractPalette(decodePng(await readFile30(abs)), 12));
21696
21935
  } catch {
21697
21936
  }
21698
21937
  }
@@ -21918,13 +22157,33 @@ async function runAudit(args) {
21918
22157
  }
21919
22158
  if (args.check && reports.some((report) => !report.evaluation.safe)) process.exitCode = 1;
21920
22159
  }
22160
+ async function runHash(args) {
22161
+ const { specs, lock } = await openProject2(args);
22162
+ if (!args.assets.length && !args.styles.length && !args.all) {
22163
+ throw new UsageError("hash needs --only <asset>, --style <style>, or --all.");
22164
+ }
22165
+ const reports = await reportSpecHashes(specs, lock);
22166
+ if (args.json) {
22167
+ log(JSON.stringify({ items: reports }, null, 2));
22168
+ return;
22169
+ }
22170
+ for (const report of reports) {
22171
+ const state = !report.lock ? "no lock entry" : report.lock.matches ? "lock matches" : "lock differs";
22172
+ log(` ${report.key}`);
22173
+ log(` spec hash ${report.specHash}`);
22174
+ log(` file hash ${report.fileSha256 ?? "(no file)"}`);
22175
+ log(` ${state}`);
22176
+ }
22177
+ log(`
22178
+ \`pixelkiln adopt --local\` writes the entry above for files with no lock entry.`);
22179
+ }
21921
22180
 
21922
22181
  // src/cli/commands/pack.ts
21923
22182
  import path44 from "path";
21924
- import { readFile as readFile30 } from "fs/promises";
22183
+ import { readFile as readFile31 } from "fs/promises";
21925
22184
 
21926
22185
  // src/pipeline/pack.ts
21927
- import { readFileSync as readFileSync6 } from "fs";
22186
+ import { readFileSync as readFileSync7 } from "fs";
21928
22187
  import path43 from "path";
21929
22188
  var DEFAULT_FRAME_SET_FPS = 12;
21930
22189
  function resolvePackInputs(raw, inputsFilePath) {
@@ -21958,7 +22217,7 @@ function packSprites(inputs, options = {}) {
21958
22217
  for (const input of ordered) {
21959
22218
  let sourceHash = null;
21960
22219
  try {
21961
- const bytes = readFileSync6(input.path);
22220
+ const bytes = readFileSync7(input.path);
21962
22221
  sourceHash = sha256(bytes);
21963
22222
  const png = decodePng(bytes);
21964
22223
  sprites.push({ id: input.id, width: png.width, height: png.height, pixels: png.pixels });
@@ -22117,7 +22376,7 @@ function mountSprites(placements, options) {
22117
22376
  for (const p of placements) {
22118
22377
  let sourceHash = null;
22119
22378
  try {
22120
- const bytes = readFileSync6(p.path);
22379
+ const bytes = readFileSync7(p.path);
22121
22380
  sourceHash = sha256(bytes);
22122
22381
  const png = decodePng(bytes);
22123
22382
  if (png.width > cellWidth || png.height > cellHeight) {
@@ -22221,7 +22480,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
22221
22480
  `Nothing to mount for style "${styleId}": ${ids.length} asset(s) declare a cell, but none has generated output or a \`source\`. Run \`pixelkiln gen --style ${styleId}\`, or point each at a file.${detail}`
22222
22481
  );
22223
22482
  }
22224
- const basePng = mount.base ? readFileSync6(path43.resolve(manifestDir, mount.base)) : void 0;
22483
+ const basePng = mount.base ? readFileSync7(path43.resolve(manifestDir, mount.base)) : void 0;
22225
22484
  const mounted = mountSprites(placements, {
22226
22485
  cellWidth: mount.cellWidth,
22227
22486
  cellHeight: mount.cellHeight,
@@ -22635,7 +22894,7 @@ async function runPack(args) {
22635
22894
  if (args.primaryOnly || args.outputRoles.length) {
22636
22895
  throw new Error("--primary-only and --output-role require manifest-driven pack");
22637
22896
  }
22638
- const raw = JSON.parse(await readFile30(path44.resolve(args.inputs), "utf8"));
22897
+ const raw = JSON.parse(await readFile31(path44.resolve(args.inputs), "utf8"));
22639
22898
  const inputs = resolvePackInputs(raw, args.inputs);
22640
22899
  const { png, atlas, skipped, sources } = packSprites(inputs, { columns: args.columns });
22641
22900
  const format = sheetFormat(args);
@@ -22860,7 +23119,7 @@ function sheetFormat(args) {
22860
23119
  }
22861
23120
 
22862
23121
  // src/cli/commands/pixellab-utils.ts
22863
- import { readFile as readFile31 } from "fs/promises";
23122
+ import { readFile as readFile32 } from "fs/promises";
22864
23123
  import path45 from "path";
22865
23124
  function loadKeys(args) {
22866
23125
  loadEnvFiles(path45.dirname(path45.resolve(args.manifest)));
@@ -23078,7 +23337,7 @@ async function runVfxArtist(args, out) {
23078
23337
  }
23079
23338
  if (args.name && args.name.length > 80) throw new UsageError("vfx --description takes a --name of at most 80 characters");
23080
23339
  const paths = vfxOutputPaths(out);
23081
- const side = args.sprite ? vfxArtistSprite(await readFile31(args.sprite), args.sprite).side : "none";
23340
+ const side = args.sprite ? vfxArtistSprite(await readFile32(args.sprite), args.sprite).side : "none";
23082
23341
  const conversation = args.effect ? await readVfxConversation(paths.provenance, args.effect) : void 0;
23083
23342
  const quote = vfxArtistQuote(artist, args.effect && !args.sprite ? "unknown" : side, Boolean(conversation));
23084
23343
  const ceiling = vfxArtistCeiling(quote);
@@ -23136,12 +23395,12 @@ async function runVfxArtist(args, out) {
23136
23395
 
23137
23396
  // src/cli/commands/quality.ts
23138
23397
  import path47 from "path";
23139
- import { readFile as readFile33 } from "fs/promises";
23398
+ import { readFile as readFile34 } from "fs/promises";
23140
23399
 
23141
23400
  // src/pipeline/quality-regression.ts
23142
23401
  import path46 from "path";
23143
- import { existsSync as existsSync35 } from "fs";
23144
- import { readFile as readFile32 } from "fs/promises";
23402
+ import { existsSync as existsSync37 } from "fs";
23403
+ import { readFile as readFile33 } from "fs/promises";
23145
23404
  import { z as z13 } from "zod";
23146
23405
  var SHA256_RE = /^[0-9a-f]{64}$/;
23147
23406
  var HEX_RE = /^#[0-9a-f]{6}$/;
@@ -23297,7 +23556,7 @@ async function measureImageQuality(file) {
23297
23556
  const absolute = path46.resolve(file);
23298
23557
  let bytes;
23299
23558
  try {
23300
- bytes = await readFile32(absolute);
23559
+ bytes = await readFile33(absolute);
23301
23560
  } catch (error) {
23302
23561
  throw new Error(`Cannot read quality image ${absolute}: ${message4(error)}`, { cause: error });
23303
23562
  }
@@ -23383,8 +23642,8 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
23383
23642
  cases
23384
23643
  });
23385
23644
  const data = Buffer.from(JSON.stringify(baseline, null, 2) + "\n");
23386
- if (existsSync35(absolute) && !options.force) {
23387
- const current = await readFile32(absolute);
23645
+ if (existsSync37(absolute) && !options.force) {
23646
+ const current = await readFile33(absolute);
23388
23647
  if (!current.equals(data)) {
23389
23648
  throw new OverwriteRefusedError(
23390
23649
  `Quality baseline already exists with different content: ${absolute}. Pass --force to replace it.`,
@@ -23395,19 +23654,90 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
23395
23654
  const result = await writeArtifactBundle([{ path: absolute, data }]);
23396
23655
  return { baseline, path: absolute, changed: result.changed.length > 0 };
23397
23656
  }
23657
+ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
23658
+ const absolute = path46.resolve(baselinePath);
23659
+ if (!existsSync37(absolute)) {
23660
+ throw new Error(`quality snapshot --only updates an existing baseline; ${absolute} does not exist. Run a full snapshot first.`);
23661
+ }
23662
+ let raw;
23663
+ try {
23664
+ raw = JSON.parse(await readFile33(absolute, "utf8"));
23665
+ } catch (error) {
23666
+ throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
23667
+ }
23668
+ if (!Array.isArray(raw.cases)) throw new Error(`Quality baseline ${absolute} has no cases array.`);
23669
+ const byId = new Map(inputs.map((input) => [input.id, input]));
23670
+ const unknown = only.filter((id) => !byId.has(id));
23671
+ if (unknown.length) {
23672
+ throw new Error(`--only names ${unknown.join(", ")}, which the quality inputs do not list. Known: ${[...byId.keys()].sort().join(", ")}`);
23673
+ }
23674
+ const root = path46.dirname(absolute);
23675
+ const cases = [...raw.cases];
23676
+ const report = [];
23677
+ for (const id of only) {
23678
+ const input = byId.get(id);
23679
+ if (path46.resolve(input.file) === absolute || input.record && path46.resolve(input.record) === absolute) {
23680
+ throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
23681
+ }
23682
+ const expected = await measureImageQuality(input.file);
23683
+ let record;
23684
+ if (input.record) {
23685
+ await verifyRecordForImage(input.record, input.file);
23686
+ record = { path: portableRelative2(root, input.record), sha256: await sha256File(input.record) };
23687
+ }
23688
+ const index = cases.findIndex((entry) => entry.id === id);
23689
+ const before = index >= 0 ? cases[index].expected ?? {} : {};
23690
+ const next = {
23691
+ id,
23692
+ file: portableRelative2(root, input.file),
23693
+ ...record ? { record } : {},
23694
+ expected,
23695
+ tolerances: index >= 0 && cases[index].tolerances ? cases[index].tolerances : input.tolerances
23696
+ };
23697
+ if (index >= 0) cases[index] = next;
23698
+ else cases.push(next);
23699
+ const changes = [];
23700
+ for (const metric of Object.keys(expected)) {
23701
+ if (JSON.stringify(before[metric]) !== JSON.stringify(expected[metric])) {
23702
+ changes.push({ metric, before: before[metric] ?? null, after: expected[metric] });
23703
+ }
23704
+ }
23705
+ report.push({ id, kind: index < 0 ? "added" : changes.length ? "updated" : "unchanged", changes });
23706
+ }
23707
+ const baseline = QualityBaselineSchema.parse({ ...raw, cases });
23708
+ const data = Buffer.from(JSON.stringify({ ...raw, cases }, null, 2) + "\n");
23709
+ const current = await readFile33(absolute);
23710
+ const changed = !current.equals(data);
23711
+ if (changed && !options.dryRun) await writeArtifactBundle([{ path: absolute, data }]);
23712
+ return { baseline, path: absolute, changed, cases: report };
23713
+ }
23398
23714
  async function readQualityBaseline(baselinePath) {
23399
23715
  const absolute = path46.resolve(baselinePath);
23400
23716
  let raw;
23401
23717
  try {
23402
- raw = JSON.parse(await readFile32(absolute, "utf8"));
23718
+ raw = JSON.parse(await readFile33(absolute, "utf8"));
23403
23719
  } catch (error) {
23404
23720
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
23405
23721
  }
23406
23722
  const parsed = QualityBaselineSchema.safeParse(raw);
23407
23723
  if (!parsed.success) {
23724
+ const cases = raw?.cases;
23725
+ const where = (issuePath) => {
23726
+ if (issuePath[0] === "cases" && typeof issuePath[1] === "number") {
23727
+ const id = cases?.[issuePath[1]]?.id;
23728
+ const rest = issuePath.slice(2).join(".");
23729
+ return typeof id === "string" ? `cases[${id}]${rest ? `.${rest}` : ""}` : issuePath.join(".");
23730
+ }
23731
+ return issuePath.join(".") || "$";
23732
+ };
23733
+ const missing = [...new Set(parsed.error.issues.flatMap((issue) => {
23734
+ const id = issue.path[0] === "cases" && typeof issue.path[1] === "number" ? cases?.[issue.path[1]]?.id : void 0;
23735
+ return issue.code === "invalid_type" && issue.received === "undefined" && typeof id === "string" ? [id] : [];
23736
+ }))];
23408
23737
  throw new Error(
23409
23738
  `Invalid quality baseline ${absolute}:
23410
- ` + parsed.error.issues.map((issue) => ` ${issue.path.join(".") || "$"}: ${issue.message}`).join("\n")
23739
+ ` + parsed.error.issues.map((issue) => ` ${where(issue.path)}: ${issue.message}`).join("\n") + (missing.length ? `
23740
+ Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${path46.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
23411
23741
  );
23412
23742
  }
23413
23743
  return parsed.data;
@@ -23529,7 +23859,7 @@ async function runQuality(args) {
23529
23859
  if (!args.out) throw new Error("quality snapshot needs --out <pixelkiln.quality.json>.");
23530
23860
  let raw;
23531
23861
  try {
23532
- raw = JSON.parse(await readFile33(path47.resolve(args.inputs), "utf8"));
23862
+ raw = JSON.parse(await readFile34(path47.resolve(args.inputs), "utf8"));
23533
23863
  } catch (error) {
23534
23864
  throw new Error(
23535
23865
  `Could not read quality inputs ${path47.resolve(args.inputs)}: ${error instanceof Error ? error.message : String(error)}`,
@@ -23540,6 +23870,23 @@ async function runQuality(args) {
23540
23870
  if (path47.resolve(args.inputs) === path47.resolve(args.out)) {
23541
23871
  throw new Error("quality snapshot --out must not overwrite its --inputs file.");
23542
23872
  }
23873
+ if (args.assets.length) {
23874
+ const result2 = await snapshotQualityCases(inputs, args.out, args.assets, { dryRun: args.dryRun });
23875
+ if (args.json) {
23876
+ log(JSON.stringify({ version: 1, path: result2.path, changed: result2.changed, dryRun: args.dryRun, cases: result2.cases }, null, 2));
23877
+ return;
23878
+ }
23879
+ for (const entry of result2.cases ?? []) {
23880
+ log(` ${entry.kind === "unchanged" ? "unchanged" : args.dryRun ? `would ${entry.kind === "added" ? "add" : "update"}` : entry.kind} ${entry.id}`);
23881
+ for (const c of entry.changes) log(` ${c.metric}: ${JSON.stringify(c.before)} -> ${JSON.stringify(c.after)}`);
23882
+ }
23883
+ log(
23884
+ `
23885
+ ${result2.changed ? args.dryRun ? "would write" : "wrote" : "no changes to"} ${path47.relative(process.cwd(), result2.path)}; other cases left as they were.`
23886
+ );
23887
+ return;
23888
+ }
23889
+ if (args.dryRun) throw new Error("quality snapshot --dry-run applies to a partial re-snapshot; add --only <id,...>.");
23543
23890
  const result = await snapshotQualityBaseline(inputs, args.out, { force: args.force });
23544
23891
  if (args.json) {
23545
23892
  log(JSON.stringify({
@@ -23580,8 +23927,8 @@ import path49 from "path";
23580
23927
 
23581
23928
  // src/recipes.ts
23582
23929
  import path48 from "path";
23583
- import { existsSync as existsSync36 } from "fs";
23584
- import { readdir as readdir3, readFile as readFile34 } from "fs/promises";
23930
+ import { existsSync as existsSync38 } from "fs";
23931
+ import { readdir as readdir3, readFile as readFile35 } from "fs/promises";
23585
23932
  import { fileURLToPath as fileURLToPath2 } from "url";
23586
23933
  import { z as z14 } from "zod";
23587
23934
  var SHA256_RE2 = /^[0-9a-f]{64}$/;
@@ -23769,7 +24116,7 @@ async function readRecipeFile(recipePath, bundled) {
23769
24116
  const absolute = path48.resolve(recipePath);
23770
24117
  let raw;
23771
24118
  try {
23772
- raw = JSON.parse(await readFile34(absolute, "utf8"));
24119
+ raw = JSON.parse(await readFile35(absolute, "utf8"));
23773
24120
  } catch (error) {
23774
24121
  throw new Error(`Could not read recipe ${absolute}: ${message5(error)}`, { cause: error });
23775
24122
  }
@@ -23783,7 +24130,7 @@ async function readRecipeFile(recipePath, bundled) {
23783
24130
  return { recipe: parsed.data, authored: raw, path: absolute, dir: path48.dirname(absolute), bundled };
23784
24131
  }
23785
24132
  async function walkRecipeFiles(root) {
23786
- if (!existsSync36(root)) return [];
24133
+ if (!existsSync38(root)) return [];
23787
24134
  const out = [];
23788
24135
  for (const entry of await readdir3(root, { withFileTypes: true })) {
23789
24136
  const resolved = path48.join(root, entry.name);
@@ -23821,7 +24168,7 @@ function parseSelector(selector) {
23821
24168
  }
23822
24169
  async function resolveRecipe(target, bundledRoot = bundledRecipeRoot()) {
23823
24170
  const local = path48.resolve(target);
23824
- if (existsSync36(local)) {
24171
+ if (existsSync38(local)) {
23825
24172
  const recipePath = path48.basename(local) === RECIPE_FILE ? local : path48.join(local, RECIPE_FILE);
23826
24173
  return readRecipeFile(recipePath, false);
23827
24174
  }
@@ -23837,7 +24184,7 @@ async function resolveRecipe(target, bundledRoot = bundledRecipeRoot()) {
23837
24184
  }
23838
24185
  async function verifyFile(root, file) {
23839
24186
  const absolute = path48.resolve(root, ...file.path.split("/"));
23840
- if (!existsSync36(absolute)) {
24187
+ if (!existsSync38(absolute)) {
23841
24188
  return { path: file.path, expectedSha256: file.sha256, actualSha256: null, status: "missing" };
23842
24189
  }
23843
24190
  const actualSha256 = await sha256File(absolute);
@@ -23911,12 +24258,12 @@ async function installRecipe(target, options = {}) {
23911
24258
  ];
23912
24259
  const files = await Promise.all(sources.map(async (file) => ({
23913
24260
  path: path48.join(destination, ...file.path.split("/")),
23914
- data: await readFile34(file.source)
24261
+ data: await readFile35(file.source)
23915
24262
  })));
23916
24263
  if (!options.force) {
23917
24264
  for (const file of files) {
23918
- if (!existsSync36(file.path)) continue;
23919
- const current = await readFile34(file.path);
24265
+ if (!existsSync38(file.path)) continue;
24266
+ const current = await readFile35(file.path);
23920
24267
  if (!current.equals(file.data)) {
23921
24268
  throw new OverwriteRefusedError(
23922
24269
  `Recipe destination has local changes: ${file.path}. Choose another --out or pass --force to replace declared recipe files.`,
@@ -24155,8 +24502,8 @@ async function runRefine(args) {
24155
24502
 
24156
24503
  // src/cli/commands/skeleton.ts
24157
24504
  import path51 from "path";
24158
- import { existsSync as existsSync37 } from "fs";
24159
- import { readFile as readFile35, writeFile as writeFile20 } from "fs/promises";
24505
+ import { existsSync as existsSync39 } from "fs";
24506
+ import { readFile as readFile36, writeFile as writeFile20 } from "fs/promises";
24160
24507
 
24161
24508
  // src/skeleton-preview.ts
24162
24509
  var RIGHT = [255, 140, 40, 255];
@@ -24267,12 +24614,12 @@ var Canvas = class {
24267
24614
  async function runEstimateSkeleton(args) {
24268
24615
  const image = args.target;
24269
24616
  if (!image) throw new UsageError("estimate-skeleton needs an image path: pixelkiln estimate-skeleton <image> [--out keypoints.json]");
24270
- if (args.out && existsSync37(path51.resolve(args.out)) && !args.force) {
24617
+ if (args.out && existsSync39(path51.resolve(args.out)) && !args.force) {
24271
24618
  throw new UsageError(`${args.out} already exists; pass --force to replace it`);
24272
24619
  }
24273
24620
  loadEnvFiles(path51.dirname(path51.resolve(args.manifest)));
24274
24621
  loadEnvFiles(process.cwd());
24275
- const bytes = await readFile35(path51.resolve(image));
24622
+ const bytes = await readFile36(path51.resolve(image));
24276
24623
  const metadata = imageMetadata(bytes);
24277
24624
  if (!metadata) throw new UsageError(`${image} is not a readable PNG or JPEG`);
24278
24625
  const sizeProblem = estimateSkeletonSizeProblem(metadata.width, metadata.height);
@@ -24313,20 +24660,20 @@ async function runSkeletonPreview(args) {
24313
24660
  sourceFile = args.from ? path51.resolve(args.from) : spec.revision.sourceFile;
24314
24661
  label = `${spec.styleId}/${spec.assetId}`;
24315
24662
  }
24316
- if (!existsSync37(keypointsFile)) throw new UsageError(`Keypoints file does not exist yet: ${keypointsFile}`);
24663
+ if (!existsSync39(keypointsFile)) throw new UsageError(`Keypoints file does not exist yet: ${keypointsFile}`);
24317
24664
  let json;
24318
24665
  try {
24319
- json = JSON.parse(await readFile35(keypointsFile, "utf8"));
24666
+ json = JSON.parse(await readFile36(keypointsFile, "utf8"));
24320
24667
  } catch (error) {
24321
24668
  throw new UsageError(`${keypointsFile} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
24322
24669
  }
24323
24670
  const set = parseSkeletonSet(json, keypointsFile);
24324
24671
  let source;
24325
24672
  if (sourceFile) {
24326
- if (!existsSync37(sourceFile)) {
24673
+ if (!existsSync39(sourceFile)) {
24327
24674
  log(` source image does not exist yet, drawing on a plain ground: ${sourceFile}`);
24328
24675
  } else {
24329
- const bytes = await readFile35(sourceFile);
24676
+ const bytes = await readFile36(sourceFile);
24330
24677
  if (imageMetadata(bytes)?.format !== "png") throw new UsageError(`${sourceFile} must be a PNG to preview over`);
24331
24678
  source = decodePng(bytes);
24332
24679
  }
@@ -24381,7 +24728,7 @@ async function runTools(args) {
24381
24728
 
24382
24729
  // src/cli/commands/workspace.ts
24383
24730
  import path52 from "path";
24384
- import { existsSync as existsSync38 } from "fs";
24731
+ import { existsSync as existsSync40 } from "fs";
24385
24732
  async function runWorkspace(args) {
24386
24733
  const workspacePath = path52.resolve(args.workspace ?? "pixelkiln.workspace.json");
24387
24734
  const dir = path52.dirname(workspacePath);
@@ -24411,7 +24758,7 @@ async function runWorkspace(args) {
24411
24758
  log(` registered "${id}" in ${path52.relative(process.cwd(), workspacePath)}`);
24412
24759
  log(` manifest: ${project.manifest}`);
24413
24760
  log(` lock: ${project.lock}`);
24414
- if (!existsSync38(lockPath)) {
24761
+ if (!existsSync40(lockPath)) {
24415
24762
  log(
24416
24763
  ` warning: no lockfile there yet; this project contributes no claims until one is generated`
24417
24764
  );
@@ -24435,7 +24782,7 @@ async function runWorkspace(args) {
24435
24782
  return;
24436
24783
  }
24437
24784
  if (args.subcommand === "list") {
24438
- if (!existsSync38(workspacePath)) {
24785
+ if (!existsSync40(workspacePath)) {
24439
24786
  throw new Error(`Workspace catalog not found: ${workspacePath}`);
24440
24787
  }
24441
24788
  const ws = await loadWorkspace(workspacePath);
@@ -24455,7 +24802,7 @@ async function runWorkspace(args) {
24455
24802
  return;
24456
24803
  }
24457
24804
  if (args.subcommand === "status") {
24458
- if (!existsSync38(workspacePath)) {
24805
+ if (!existsSync40(workspacePath)) {
24459
24806
  throw new Error(`Workspace catalog not found: ${workspacePath}`);
24460
24807
  }
24461
24808
  const ws = await loadWorkspace(workspacePath);
@@ -24517,8 +24864,8 @@ async function runHelp() {
24517
24864
  async function runVersion() {
24518
24865
  for (const up of ["../package.json", "../../package.json"]) {
24519
24866
  const url = new URL(up, import.meta.url);
24520
- if (!existsSync39(url)) continue;
24521
- const pkg = JSON.parse(await readFile36(url, "utf8"));
24867
+ if (!existsSync41(url)) continue;
24868
+ const pkg = JSON.parse(await readFile37(url, "utf8"));
24522
24869
  if (pkg.name === "pixelkiln") {
24523
24870
  log(`${pkg.name} ${pkg.version}`);
24524
24871
  return;
@@ -24534,6 +24881,7 @@ var RUNNERS = {
24534
24881
  "-v": runVersion,
24535
24882
  init: runInit,
24536
24883
  plan: runPlan,
24884
+ hash: runHash,
24537
24885
  doctor: runDoctor,
24538
24886
  gen: runGenerate,
24539
24887
  submit: runGenerate,