ntn-skills 0.1.2 → 0.2.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.
@@ -4,7 +4,7 @@
4
4
  import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
7
- import { Cause, Effect as Effect8, Layer as Layer3, Option, Stdio, Stream as Stream3 } from "effect";
7
+ import { Cause, Effect as Effect14, Layer as Layer4, Option, Stdio, Stream as Stream3 } from "effect";
8
8
  import { Argument, CliConfig, CliError, CliOutput, Command, Flag, GlobalFlag } from "effect/cli";
9
9
 
10
10
  // packages/core/src/model.ts
@@ -98,12 +98,28 @@ var SnapshotSchema = Schema.Struct({
98
98
  skill_name: Schema.String,
99
99
  version_id: Schema.String,
100
100
  created_at: Schema.Number,
101
- files: Schema.Array(FileEntrySchema)
101
+ files: Schema.Array(FileEntrySchema),
102
+ references: Schema.optional(Schema.Array(Schema.Struct({ id: Schema.String, path: Schema.String, markdown: Schema.String })))
102
103
  });
103
104
  var ConfigSchema = Schema.Struct({
104
105
  sources: Schema.optional(Schema.Array(SourceSchema)),
105
106
  default_database: Schema.optional(Schema.String),
106
- token: Schema.optional(Schema.String)
107
+ token: Schema.optional(Schema.String),
108
+ cache_policy: Schema.optional(Schema.Struct({
109
+ read_max_age_ms: Schema.Number,
110
+ catalog_max_age_ms: Schema.Number
111
+ })),
112
+ sync_bindings: Schema.optional(Schema.Array(Schema.Struct({
113
+ id: Schema.String,
114
+ label: Schema.String,
115
+ page_id: Schema.String,
116
+ database_id: Schema.String,
117
+ data_source_id: Schema.String,
118
+ scope: Schema.String,
119
+ logical_path: Schema.String,
120
+ active: Schema.Boolean,
121
+ revision: Schema.Number
122
+ })))
107
123
  });
108
124
  function decode(schema, input) {
109
125
  try {
@@ -265,48 +281,261 @@ function parseTarget(input, path) {
265
281
  return { ...target, path: path === undefined ? target.path : normalizePath(path) };
266
282
  }
267
283
  // packages/core/src/notion.ts
268
- import { Context as Context2, Crypto as Crypto2, Effect as Effect2, Layer as Layer2, Stream } from "effect";
284
+ import { Context as Context2, Crypto as Crypto2, Effect as Effect3, Layer as Layer2, Stream } from "effect";
269
285
  import { ChildProcess, ChildProcessSpawner } from "effect/process";
270
286
 
271
287
  // packages/core/src/store.ts
272
- import { Context, Crypto, Effect, FileSystem, Layer, Path } from "effect";
288
+ import { Context, Crypto, Effect as Effect2, FileSystem, Layer, Path, Schema as Schema2 } from "effect";
289
+
290
+ // packages/core/src/local-locks.ts
291
+ import { Effect } from "effect";
292
+ import { execFile } from "node:child_process";
293
+ import { createHash, randomUUID } from "node:crypto";
294
+ import * as fs from "node:fs/promises";
295
+ import { hostname } from "node:os";
296
+ import * as path from "node:path";
297
+ var asError = (error) => {
298
+ if (error instanceof SkillsError)
299
+ return error;
300
+ const code = error !== null && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : undefined;
301
+ return fail("STORAGE_ERROR", "The local retention or lock operation failed.", {
302
+ syscall_code: code
303
+ });
304
+ };
305
+ async function retainInTrash(location) {
306
+ if (process.platform !== "darwin")
307
+ throw fail("RETENTION_UNAVAILABLE", "System Trash is required; bytes have been retained in place.", { path: location });
308
+ try {
309
+ await fs.access("/usr/bin/trash", fs.constants.X_OK);
310
+ } catch {
311
+ throw fail("RETENTION_UNAVAILABLE", "The /usr/bin/trash capability is required; bytes have been retained in place.", { path: location });
312
+ }
313
+ await new Promise((resolve, reject) => execFile("/usr/bin/trash", [location], (error) => error ? reject(fail("RETENTION_FAILED", "System Trash failed; retained bytes remain available.", {
314
+ path: location
315
+ })) : resolve()));
316
+ }
317
+ var trashPath = (location) => Effect.tryPromise({ try: () => retainInTrash(location), catch: asError });
318
+ function withLocalLocks(stateRoot, keys, effect) {
319
+ const release = async (locks) => {
320
+ for (const location of [...locks].reverse()) {
321
+ const retired = `${location}.${randomUUID()}.released`;
322
+ await fs.rename(location, retired);
323
+ if (process.platform === "darwin") {
324
+ try {
325
+ await retainInTrash(retired);
326
+ } catch {}
327
+ }
328
+ }
329
+ };
330
+ const acquire = async () => {
331
+ const locksRoot = path.join(stateRoot, "sync", "locks");
332
+ await fs.mkdir(locksRoot, { recursive: true, mode: 448 });
333
+ const acquired = [];
334
+ try {
335
+ for (const key of [...new Set(keys)].sort()) {
336
+ const location = path.join(locksRoot, createHash("sha256").update(key).digest("hex"));
337
+ try {
338
+ await fs.mkdir(location, { mode: 448 });
339
+ } catch (error) {
340
+ if (error === null || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST")
341
+ throw error;
342
+ const identity = await fs.lstat(location, { bigint: true });
343
+ let owner = {};
344
+ try {
345
+ const raw = property(JSON.parse(await fs.readFile(path.join(location, "owner.json"), "utf8")));
346
+ owner = {
347
+ ...typeof raw.pid === "number" && Number.isSafeInteger(raw.pid) && raw.pid > 0 ? { pid: raw.pid } : {},
348
+ same_host: raw.host === hostname()
349
+ };
350
+ } catch {}
351
+ let dead = false;
352
+ if (owner.same_host && owner.pid !== undefined) {
353
+ try {
354
+ process.kill(owner.pid, 0);
355
+ } catch (error) {
356
+ dead = error !== null && typeof error === "object" && "code" in error && error.code === "ESRCH";
357
+ }
358
+ }
359
+ if (!dead)
360
+ throw fail("SYNC_LOCKED", "A live or unidentifiable process owns this fence.", {
361
+ key,
362
+ lock_path: location,
363
+ owner
364
+ });
365
+ try {
366
+ await fs.mkdir(path.join(location, "recovery"), { mode: 448 });
367
+ } catch {
368
+ throw fail("SYNC_LOCKED", "Another process is retaining the dead lock.", {
369
+ key,
370
+ lock_path: location
371
+ });
372
+ }
373
+ const latest = await fs.lstat(location, { bigint: true });
374
+ if (latest.dev !== identity.dev || latest.ino !== identity.ino)
375
+ throw fail("SYNC_LOCKED", "Lock identity changed during recovery.", { key });
376
+ await fs.rename(location, `${location}.${randomUUID()}.crashed`);
377
+ try {
378
+ await fs.mkdir(location, { mode: 448 });
379
+ } catch {
380
+ throw fail("SYNC_LOCKED", "Another process acquired the recovered fence.", { key });
381
+ }
382
+ }
383
+ acquired.push(location);
384
+ await fs.writeFile(path.join(location, "owner.json"), JSON.stringify({ pid: process.pid, host: hostname(), operation_id: randomUUID(), key }), { flag: "wx", mode: 384 });
385
+ }
386
+ return acquired;
387
+ } catch (error) {
388
+ await release(acquired);
389
+ throw error;
390
+ }
391
+ };
392
+ return Effect.acquireUseRelease(Effect.tryPromise({ try: acquire, catch: asError }), () => effect, (locks) => Effect.tryPromise({ try: () => release(locks), catch: asError }).pipe(Effect.orDie));
393
+ }
394
+
395
+ // packages/core/src/store.ts
273
396
  class Store extends Context.Service()("ntn-skills/Store") {
274
397
  }
275
- var StoreLive = Layer.effect(Store, Effect.gen(function* () {
398
+ var StoreLive = Layer.effect(Store, Effect2.gen(function* () {
276
399
  const fs = yield* FileSystem.FileSystem;
277
400
  const path = yield* Path.Path;
278
401
  const crypto = yield* Crypto.Crypto;
279
402
  const home = process.env.HOME ?? process.env.USERPROFILE;
280
403
  if (!process.env.NTN_SKILLS_HOME && !process.env.XDG_STATE_HOME && !home) {
281
- return yield* Effect.fail(fail("CONFIG_ERROR", "Set NTN_SKILLS_HOME or HOME to select the local state directory."));
404
+ return yield* Effect2.fail(fail("CONFIG_ERROR", "Set NTN_SKILLS_HOME or HOME to select the local state directory."));
282
405
  }
283
406
  if (!process.env.NTN_SKILLS_CONFIG_HOME && !process.env.XDG_CONFIG_HOME && !home) {
284
- return yield* Effect.fail(fail("CONFIG_ERROR", "Set NTN_SKILLS_CONFIG_HOME or HOME to select the configuration directory."));
407
+ return yield* Effect2.fail(fail("CONFIG_ERROR", "Set NTN_SKILLS_CONFIG_HOME or HOME to select the configuration directory."));
285
408
  }
286
409
  const root = path.resolve(process.env.NTN_SKILLS_HOME ?? path.join(process.env.XDG_STATE_HOME ?? path.join(home, ".local", "state"), "ntn-skills"));
287
410
  const configRoot = path.resolve(process.env.NTN_SKILLS_CONFIG_HOME ?? path.join(process.env.XDG_CONFIG_HOME ?? path.join(home, ".config"), "ntn-skills"));
288
- const location = (key) => path.join(key === "config.json" ? configRoot : root, key);
289
- const writeBytes = (key, bytes) => Effect.gen(function* () {
411
+ if (!process.env.NTN_SKILLS_CACHE_HOME && !process.env.XDG_CACHE_HOME && !home)
412
+ return yield* Effect2.fail(fail("CONFIG_ERROR", "Set NTN_SKILLS_CACHE_HOME or HOME to select the cache directory."));
413
+ const cacheRoot = path.resolve(process.env.NTN_SKILLS_CACHE_HOME ?? path.join(process.env.XDG_CACHE_HOME ?? path.join(home, ".cache"), "ntn-skills"));
414
+ const location = (key) => key === "cache" ? cacheRoot : key.startsWith("cache/") ? path.join(cacheRoot, key.slice(6)) : path.join(key === "config.json" ? configRoot : root, key);
415
+ const writeBytes = (key, bytes) => Effect2.gen(function* () {
290
416
  const destination = location(key);
291
417
  yield* fs.makeDirectory(path.dirname(destination), { recursive: true, mode: 448 });
292
418
  const id = yield* crypto.randomUUIDv4();
293
419
  const staged = `${destination}.${id}.pending`;
294
420
  yield* fs.writeFile(staged, bytes, { flag: "wx", mode: 384 });
295
421
  yield* fs.rename(staged, destination);
296
- }).pipe(Effect.mapError(() => fail("STORAGE_ERROR", "Could not atomically write local state.", { key })));
422
+ }).pipe(Effect2.mapError(() => fail("STORAGE_ERROR", "Could not atomically write local state.", { key })));
423
+ const GenerationSchema = Schema2.Struct({
424
+ generation: Schema2.Number,
425
+ retired_through: Schema2.optional(Schema2.Number)
426
+ });
427
+ const generationState = (scope, pageId) => Effect2.gen(function* () {
428
+ const key = `cache-generations/${scope}/${pageId}.json`;
429
+ if (!(yield* fs.exists(location(key))))
430
+ return { generation: 0, retired_through: 0 };
431
+ const raw = yield* fs.readFileString(location(key));
432
+ return yield* Effect2.try({
433
+ try: () => {
434
+ const value = decode(GenerationSchema, JSON.parse(raw));
435
+ if (!Number.isSafeInteger(value.generation) || value.generation < 0 || value.retired_through !== undefined && (!Number.isSafeInteger(value.retired_through) || value.retired_through < 0))
436
+ throw fail("STATE_CORRUPT", "Cache generation state is invalid.");
437
+ return { generation: value.generation, retired_through: value.retired_through ?? 0 };
438
+ },
439
+ catch: () => fail("STATE_CORRUPT", "Cache generation state is invalid.")
440
+ });
441
+ }).pipe(Effect2.mapError((error) => error instanceof SkillsError ? error : fail("STORAGE_ERROR", "Could not read cache generation state.")));
297
442
  return {
298
443
  root,
444
+ configRoot,
445
+ cacheRoot,
446
+ reserveCacheGeneration: (scope, pageId) => withLocalLocks(root, [`cache-generation:${scope}/${pageId}`], Effect2.gen(function* () {
447
+ if (!/^[a-f0-9]{64}$/.test(scope) || !/^[a-zA-Z0-9-]+$/.test(pageId))
448
+ return yield* Effect2.fail(fail("INVALID_ARGUMENT", "Cache generation identity is invalid."));
449
+ const key = `cache-generations/${scope}/${pageId}.json`;
450
+ const previous = yield* generationState(scope, pageId);
451
+ const generation = previous.generation + 1;
452
+ if (!Number.isSafeInteger(generation))
453
+ return yield* Effect2.fail(fail("STATE_CORRUPT", "Cache generation exhausted."));
454
+ yield* writeBytes(key, new TextEncoder().encode(JSON.stringify({ ...previous, generation })));
455
+ return generation;
456
+ })),
457
+ listKeys: (prefix) => Effect2.gen(function* () {
458
+ const directory = location(prefix);
459
+ if (!(yield* fs.exists(directory)))
460
+ return [];
461
+ const names = yield* fs.readDirectory(directory, { recursive: true });
462
+ const keys = [];
463
+ for (const name of names)
464
+ if ((yield* fs.stat(path.join(directory, name))).type === "File")
465
+ keys.push(`${prefix.replace(/\/$/, "")}/${name.split(path.sep).join("/")}`);
466
+ return keys.sort();
467
+ }).pipe(Effect2.mapError(() => fail("STORAGE_ERROR", "Could not enumerate local observations."))),
468
+ retireKeys: (keys) => Effect2.gen(function* () {
469
+ if (keys.some((key) => !key.startsWith("cache/") || !location(key).startsWith(cacheRoot + path.sep)))
470
+ return yield* Effect2.fail(fail("INVALID_ARGUMENT", "Only disposable cache observations may be retired."));
471
+ const retired = [];
472
+ const pages = [
473
+ ...new Set(keys.filter((key) => key.startsWith("cache/latest/") || key.startsWith("cache/catalogs/")).map((key) => {
474
+ const parts = key.split("/");
475
+ return `${parts[2]}/${parts[1] === "catalogs" ? `catalog-${parts[3].replace(/\.json$/, "")}` : parts[3]}`;
476
+ }))
477
+ ];
478
+ return yield* withLocalLocks(root, pages.map((page) => `cache-generation:${page}`), Effect2.gen(function* () {
479
+ for (const page of pages) {
480
+ const [scope, id] = page.split("/");
481
+ const current = yield* generationState(scope, id);
482
+ let generation = current.generation;
483
+ for (const key of keys) {
484
+ const parts = key.split("/");
485
+ const identity = parts[1] === "catalogs" ? `catalog-${parts[3].replace(/\.json$/, "")}` : parts[3];
486
+ if (parts[2] !== scope || identity !== id || !(yield* fs.exists(location(key))))
487
+ continue;
488
+ const raw = yield* fs.readFileString(location(key));
489
+ const observed = yield* Effect2.try({
490
+ try: () => decode(GenerationSchema, JSON.parse(raw)),
491
+ catch: () => fail("STATE_CORRUPT", "Observation generation is invalid.")
492
+ }).pipe(Effect2.result);
493
+ if (observed._tag === "Success")
494
+ generation = Math.max(generation, observed.success.generation);
495
+ }
496
+ yield* writeBytes(`cache-generations/${page}.json`, new TextEncoder().encode(JSON.stringify({ generation, retired_through: generation })));
497
+ }
498
+ for (const key of keys) {
499
+ if (!(yield* fs.exists(location(key))))
500
+ continue;
501
+ yield* trashPath(location(key));
502
+ retired.push({ key, retention_path: "system_trash" });
503
+ }
504
+ return retired;
505
+ }));
506
+ }).pipe(Effect2.mapError((error) => error instanceof SkillsError ? error : fail("STORAGE_ERROR", "Could not retire cache observations."))),
299
507
  writeBytes,
300
- readBytes: (key) => fs.readFile(location(key)).pipe(Effect.mapError(() => fail("SNAPSHOT_MISSING", "The requested snapshot file is unavailable locally.", {
508
+ readBytes: (key) => fs.readFile(location(key)).pipe(Effect2.mapError(() => fail("SNAPSHOT_MISSING", "The requested snapshot file is unavailable locally.", {
301
509
  key
302
510
  }))),
303
- writeJson: (key, value) => writeBytes(key, new TextEncoder().encode(JSON.stringify(value))),
304
- readJson: (key, schema) => Effect.gen(function* () {
511
+ writeJson: (key, value) => {
512
+ if (!key.startsWith("cache/latest/") && !key.startsWith("cache/catalogs/"))
513
+ return writeBytes(key, new TextEncoder().encode(JSON.stringify(value)));
514
+ const parts = key.split("/");
515
+ const scope = parts[2];
516
+ const id = parts[1] === "catalogs" ? `catalog-${parts[3].replace(/\.json$/, "")}` : parts[3];
517
+ return withLocalLocks(root, [`cache-generation:${scope}/${id}`], Effect2.gen(function* () {
518
+ const state = yield* generationState(scope, id);
519
+ if (!value || typeof value !== "object" || !("generation" in value) || typeof value.generation !== "number" || value.generation <= state.retired_through)
520
+ return yield* Effect2.fail(fail("CACHE_INVALIDATED", "An in-flight observation was retired before publication."));
521
+ if (parts[1] === "catalogs" && (yield* fs.exists(location(key)))) {
522
+ const raw = yield* fs.readFileString(location(key));
523
+ const previous = yield* Effect2.try({
524
+ try: () => decode(GenerationSchema, JSON.parse(raw)),
525
+ catch: () => fail("STATE_CORRUPT", "Catalog observation generation is invalid.")
526
+ }).pipe(Effect2.result);
527
+ if (previous._tag === "Success" && previous.success.generation > value.generation)
528
+ return;
529
+ }
530
+ yield* writeBytes(key, new TextEncoder().encode(JSON.stringify(value)));
531
+ })).pipe(Effect2.mapError((error) => error instanceof SkillsError ? error : fail("STORAGE_ERROR", "Could not publish cache observation.")));
532
+ },
533
+ readJson: (key, schema) => Effect2.gen(function* () {
305
534
  if (key === "config.json" && !(yield* fs.exists(location(key)))) {
306
535
  const legacy = path.join(root, key);
307
536
  if (yield* fs.exists(legacy)) {
308
537
  const raw = yield* fs.readFileString(legacy);
309
- yield* Effect.try({
538
+ yield* Effect2.try({
310
539
  try: () => decode(ConfigSchema, JSON.parse(raw)),
311
540
  catch: () => fail("STATE_CORRUPT", "Legacy configuration failed schema validation.")
312
541
  });
@@ -320,49 +549,61 @@ var StoreLive = Layer.effect(Store, Effect.gen(function* () {
320
549
  if (!(yield* fs.exists(location(key))))
321
550
  return;
322
551
  const raw = yield* fs.readFileString(location(key));
323
- return yield* Effect.try({
552
+ if (key.startsWith("cache/latest/") || key.startsWith("cache/catalogs/")) {
553
+ const parts = key.split("/");
554
+ const scope = parts[2];
555
+ const id = parts[1] === "catalogs" ? `catalog-${parts[3].replace(/\.json$/, "")}` : parts[3];
556
+ const state = yield* generationState(scope, id);
557
+ const generation = yield* Effect2.try({
558
+ try: () => decode(GenerationSchema, JSON.parse(raw)).generation,
559
+ catch: () => fail("STATE_CORRUPT", "Cache observation is invalid.")
560
+ });
561
+ if (generation <= state.retired_through)
562
+ return;
563
+ }
564
+ return yield* Effect2.try({
324
565
  try: () => decode(schema, JSON.parse(raw)),
325
566
  catch: () => fail("STATE_CORRUPT", "Local state failed schema validation.", { key })
326
567
  });
327
- }).pipe(Effect.mapError((e) => e instanceof SkillsError ? e : fail("STORAGE_ERROR", "Could not read local state.", { key }))),
328
- output: (destination, bytes) => Effect.gen(function* () {
568
+ }).pipe(Effect2.mapError((e) => e instanceof SkillsError ? e : fail("STORAGE_ERROR", "Could not read local state.", { key }))),
569
+ output: (destination, bytes) => Effect2.gen(function* () {
329
570
  const full = path.resolve(destination);
330
- const reuse = Effect.gen(function* () {
571
+ const reuse = Effect2.gen(function* () {
331
572
  const info = yield* fs.stat(full);
332
573
  if (info.type !== "File")
333
- return yield* Effect.fail(fail("OUTPUT_CONFLICT", "Output is not a regular file.", { output: full }));
574
+ return yield* Effect2.fail(fail("OUTPUT_CONFLICT", "Output is not a regular file.", { output: full }));
334
575
  const existing = yield* fs.readFile(full);
335
576
  if (existing.length !== bytes.length || existing.some((byte, index) => byte !== bytes[index]))
336
- return yield* Effect.fail(fail("OUTPUT_CONFLICT", "Existing output differs.", { output: full }));
577
+ return yield* Effect2.fail(fail("OUTPUT_CONFLICT", "Existing output differs.", { output: full }));
337
578
  return { output: full, reused: true };
338
579
  });
339
580
  if (yield* fs.exists(full))
340
581
  return yield* reuse;
341
- return yield* fs.writeFile(full, bytes, { flag: "wx", mode: 384 }).pipe(Effect.map(() => ({ output: full, reused: false })), Effect.catch((error) => Effect.gen(function* () {
582
+ return yield* fs.writeFile(full, bytes, { flag: "wx", mode: 384 }).pipe(Effect2.map(() => ({ output: full, reused: false })), Effect2.catch((error) => Effect2.gen(function* () {
342
583
  if (yield* fs.exists(full))
343
584
  return yield* reuse;
344
- return yield* Effect.fail(error);
585
+ return yield* Effect2.fail(error);
345
586
  })));
346
- }).pipe(Effect.mapError((error) => error instanceof SkillsError ? error : fail("OUTPUT_FAILED", "Could not write output; parent directory must exist.", {
587
+ }).pipe(Effect2.mapError((error) => error instanceof SkillsError ? error : fail("OUTPUT_FAILED", "Could not write output; parent directory must exist.", {
347
588
  destination
348
589
  })))
349
590
  };
350
591
  }));
351
- var configuration = Effect.gen(function* () {
592
+ var configuration = Effect2.gen(function* () {
352
593
  const store = yield* Store;
353
594
  return (yield* store.readJson("config.json", ConfigSchema)) ?? { sources: [] };
354
595
  });
355
- var configuredSources = configuration.pipe(Effect.map((config) => config.sources ?? []));
356
- var configuredToken = configuration.pipe(Effect.map((config) => config.token?.trim() || process.env.NOTION_API_TOKEN?.trim() || undefined));
596
+ var configuredSources = configuration.pipe(Effect2.map((config) => config.sources ?? []));
597
+ var configuredToken = configuration.pipe(Effect2.map((config) => config.token?.trim() || process.env.NOTION_API_TOKEN?.trim() || undefined));
357
598
  function publicConfiguration(config) {
358
599
  const { token, ...visible } = config;
359
600
  return { ...visible, token_configured: Boolean(token?.trim()) };
360
601
  }
361
602
  function setToken(input) {
362
- return Effect.gen(function* () {
603
+ return Effect2.gen(function* () {
363
604
  const token = input?.trim();
364
605
  if (input !== undefined && (!token || /\s/.test(token)))
365
- return yield* Effect.fail(fail("INVALID_ARGUMENT", "Provide one non-empty token through standard input."));
606
+ return yield* Effect2.fail(fail("INVALID_ARGUMENT", "Provide one non-empty token through standard input."));
366
607
  const { token: _previous, ...config } = yield* configuration;
367
608
  const next = { ...config, ...token ? { token } : {} };
368
609
  const store = yield* Store;
@@ -370,22 +611,33 @@ function setToken(input) {
370
611
  return publicConfiguration(next);
371
612
  });
372
613
  }
373
- var sha256 = (input) => Effect.gen(function* () {
614
+ var sha256 = (input) => Effect2.gen(function* () {
374
615
  const crypto = yield* Crypto.Crypto;
375
616
  const hash = yield* crypto.digest("SHA-256", typeof input === "string" ? new TextEncoder().encode(input) : input);
376
617
  return Array.from(hash, (b) => b.toString(16).padStart(2, "0")).join("");
377
- }).pipe(Effect.mapError(() => fail("CRYPTO_ERROR", "Could not compute a content identity.")));
618
+ }).pipe(Effect2.mapError(() => fail("CRYPTO_ERROR", "Could not compute a content identity.")));
378
619
 
379
620
  // packages/core/src/notion.ts
380
621
  class Notion extends Context2.Service()("ntn-skills/Notion") {
381
622
  }
382
- var NotionLive = Layer2.effect(Notion, Effect2.gen(function* () {
623
+ function transportReason(stderr) {
624
+ if (/timed? ?out|timeout/i.test(stderr))
625
+ return "timeout";
626
+ if (/dns|resolve|name.*resolution|ENOTFOUND/i.test(stderr))
627
+ return "dns";
628
+ if (/certificate|TLS|SSL/i.test(stderr))
629
+ return "tls";
630
+ if (/connect|network|request|transport|502|503|504/i.test(stderr))
631
+ return "network";
632
+ return "invalid_response";
633
+ }
634
+ var NotionLive = Layer2.effect(Notion, Effect3.gen(function* () {
383
635
  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
384
636
  const store = yield* Store;
385
637
  const crypto = yield* Crypto2.Crypto;
386
- const credential = yield* Effect2.cached(configuredToken.pipe(Effect2.provideService(Store, store)));
638
+ const credential = yield* Effect3.cached(configuredToken.pipe(Effect3.provideService(Store, store)));
387
639
  const executable = process.env.NTN_SKILLS_NTN_BIN ?? "ntn";
388
- const run = (args, body, token) => Effect2.scoped(Effect2.gen(function* () {
640
+ const run = (args, body, token) => Effect3.scoped(Effect3.gen(function* () {
389
641
  const child = yield* spawner.spawn(ChildProcess.make(executable, args, {
390
642
  stdin: body === undefined ? "ignore" : Stream.make(body),
391
643
  stdout: "pipe",
@@ -394,19 +646,19 @@ var NotionLive = Layer2.effect(Notion, Effect2.gen(function* () {
394
646
  env: { NOTION_API_TOKEN: token },
395
647
  extendEnv: true
396
648
  }));
397
- const [stdout, stderr, exit] = yield* Effect2.all([
649
+ const [stdout, stderr, exit] = yield* Effect3.all([
398
650
  child.stdout.pipe(Stream.decodeText(), Stream.runFold(() => "", (a, b) => a + b)),
399
651
  child.stderr.pipe(Stream.decodeText(), Stream.runFold(() => "", (a, b) => a + b)),
400
652
  child.exitCode
401
653
  ], { concurrency: "unbounded" });
402
654
  return { stdout, stderr, exit };
403
- })).pipe(Effect2.timeout("60 seconds"), Effect2.mapError(() => fail("NTN_UNAVAILABLE", "ntn could not complete the request. Check installation and authentication with ntn doctor.")));
655
+ })).pipe(Effect3.timeout("60 seconds"), Effect3.mapError((error) => fail("NTN_UNAVAILABLE", "ntn could not complete the request. Check installation, network and authentication with ntn doctor.", { reason: property(error)._tag === "TimeoutError" ? "timeout" : "process" })));
404
656
  return {
405
- credentialIdentity: credential.pipe(Effect2.flatMap((token) => sha256(token ?? "ntn-keychain")), Effect2.provideService(Crypto2.Crypto, crypto)),
406
- version: run(["--version"]).pipe(Effect2.flatMap((r) => r.exit === 0 ? Effect2.succeed(r.stdout.trim()) : Effect2.fail(fail("NTN_UNAVAILABLE", "ntn --version failed.")))),
407
- request: (path, body, options) => Effect2.gen(function* () {
657
+ credentialIdentity: credential.pipe(Effect3.flatMap((token) => sha256(token ?? "ntn-keychain")), Effect3.provideService(Crypto2.Crypto, crypto)),
658
+ version: run(["--version"]).pipe(Effect3.flatMap((r) => r.exit === 0 ? Effect3.succeed(r.stdout.trim()) : Effect3.fail(fail("NTN_UNAVAILABLE", "ntn --version failed.")))),
659
+ request: (path, body, options) => Effect3.gen(function* () {
408
660
  const token = yield* credential;
409
- yield* Effect2.sleep("350 millis");
661
+ yield* Effect3.sleep("350 millis");
410
662
  const args = ["api", path, "--notion-version", "2026-03-11"];
411
663
  const method = options?.method ?? (body === undefined ? "GET" : "POST");
412
664
  const mutating = method !== "GET" && path !== "v1/search" && !path.endsWith("/query");
@@ -417,18 +669,33 @@ var NotionLive = Layer2.effect(Notion, Effect2.gen(function* () {
417
669
  if (options?.file)
418
670
  args.push("--file", options.file);
419
671
  for (let attempt = 0;; attempt++) {
420
- const r = yield* run(args, payload, token).pipe(Effect2.mapError((error) => mutating ? fail("WRITE_OUTCOME_UNKNOWN", "The write may have completed; read the target before retrying.", { path, cause_code: error.code }) : error));
421
- const value = yield* Effect2.try({
672
+ const r = yield* run(args, payload, token).pipe(Effect3.mapError((error) => mutating ? fail("WRITE_OUTCOME_UNKNOWN", "The write may have completed; read the target before retrying.", { path, cause_code: error.code, cause_details: error.details }) : error));
673
+ const decoded = yield* Effect3.try({
422
674
  try: () => JSON.parse(r.stdout),
423
- catch: () => fail(mutating ? "WRITE_OUTCOME_UNKNOWN" : r.exit ? "NOTION_REQUEST_FAILED" : "INVALID_RESPONSE", "ntn returned no valid API JSON. Check ntn doctor; interactive login is never started automatically.", { path, exit_code: r.exit })
424
- });
675
+ catch: () => fail(mutating ? "WRITE_OUTCOME_UNKNOWN" : r.exit ? "NOTION_REQUEST_FAILED" : "INVALID_RESPONSE", "ntn returned no valid API JSON. Inspect reason and exit_code; check network and authentication with ntn doctor.", { path, exit_code: r.exit, reason: transportReason(r.stderr) })
676
+ }).pipe(Effect3.result);
677
+ if (decoded._tag === "Failure") {
678
+ const reason = property(decoded.failure.details).reason;
679
+ if (!mutating && r.exit !== 0 && ["dns", "network", "timeout"].includes(String(reason)) && attempt < 3) {
680
+ yield* Effect3.sleep(`${2 ** attempt} seconds`);
681
+ continue;
682
+ }
683
+ return yield* Effect3.fail(decoded.failure);
684
+ }
685
+ const value = decoded.success;
425
686
  if (value && typeof value === "object" && "object" in value && value.object === "error") {
426
- const error = yield* Effect2.try({
687
+ const error = yield* Effect3.try({
427
688
  try: () => decode(ApiErrorSchema, value),
428
689
  catch: () => fail("INVALID_RESPONSE", "Invalid Notion error response.")
429
690
  });
430
- if (!mutating && error.code === "rate_limited" && attempt < 3) {
431
- yield* Effect2.sleep(`${2 ** attempt} seconds`);
691
+ if (!mutating && [
692
+ "rate_limited",
693
+ "internal_server_error",
694
+ "service_unavailable",
695
+ "database_connection_unavailable",
696
+ "gateway_timeout"
697
+ ].includes(error.code) && attempt < 3) {
698
+ yield* Effect3.sleep(`${2 ** attempt} seconds`);
432
699
  continue;
433
700
  }
434
701
  const codes = {
@@ -438,7 +705,7 @@ var NotionLive = Layer2.effect(Notion, Effect2.gen(function* () {
438
705
  directory_not_found: "SKILL_NOT_FOUND",
439
706
  rate_limited: "RATE_LIMITED"
440
707
  };
441
- return yield* Effect2.fail(fail(mutating && ![
708
+ return yield* Effect3.fail(fail(mutating && ![
442
709
  "unauthorized",
443
710
  "restricted_resource",
444
711
  "object_not_found",
@@ -447,9 +714,10 @@ var NotionLive = Layer2.effect(Notion, Effect2.gen(function* () {
447
714
  ].includes(error.code) ? "WRITE_OUTCOME_UNKNOWN" : codes[error.code] ?? "NOTION_REQUEST_FAILED", "The Notion API request failed.", { path, notion_code: error.code, exit_code: r.exit }));
448
715
  }
449
716
  if (r.exit !== 0)
450
- return yield* Effect2.fail(fail(mutating ? "WRITE_OUTCOME_UNKNOWN" : "NOTION_REQUEST_FAILED", "ntn failed to complete the API request.", {
717
+ return yield* Effect3.fail(fail(mutating ? "WRITE_OUTCOME_UNKNOWN" : "NOTION_REQUEST_FAILED", "ntn failed to complete the API request.", {
451
718
  path,
452
- exit_code: r.exit
719
+ exit_code: r.exit,
720
+ reason: transportReason(r.stderr)
453
721
  }));
454
722
  return value;
455
723
  }
@@ -457,24 +725,364 @@ var NotionLive = Layer2.effect(Notion, Effect2.gen(function* () {
457
725
  };
458
726
  }));
459
727
  // packages/core/src/catalog.ts
460
- import { Clock, Effect as Effect3 } from "effect";
461
- var authScope = Effect3.gen(function* () {
728
+ import { Clock as Clock2, Effect as Effect5 } from "effect";
729
+
730
+ // packages/core/src/cache.ts
731
+ import { Clock, Crypto as Crypto3, Effect as Effect4, Schema as Schema3 } from "effect";
732
+ var DEFAULT_CACHE_POLICY = {
733
+ read_max_age_ms: 300000,
734
+ catalog_max_age_ms: 60000
735
+ };
736
+ function parseDuration(input) {
737
+ const match = /^(0|[0-9]+[smhd])$/.exec(input);
738
+ if (!match)
739
+ throw fail("INVALID_ARGUMENT", "Duration must be 0 or an integer followed by s, m, h or d.");
740
+ const multipliers = { s: 1000, m: 60000, h: 3600000, d: 86400000 };
741
+ const multiplier = multipliers[input.at(-1)] ?? 1;
742
+ const value = Number(input === "0" ? input : input.slice(0, -1)) * multiplier;
743
+ if (!Number.isSafeInteger(value) || value < 0)
744
+ throw fail("INVALID_ARGUMENT", "Duration exceeds the supported integer range.");
745
+ return value;
746
+ }
747
+ function validateReadPolicy(options, pinned = false) {
748
+ if (Number(Boolean(options.refresh)) + Number(Boolean(options.offline)) + Number(options.maxAge !== undefined) > 1)
749
+ throw fail("INVALID_ARGUMENT", "refresh, offline and maxAge are mutually exclusive.");
750
+ if (options.maxAge !== undefined && (!Number.isSafeInteger(options.maxAge) || options.maxAge < 0))
751
+ throw fail("INVALID_ARGUMENT", "maxAge must be a finite nonnegative integer in milliseconds.");
752
+ if (pinned && (options.refresh || options.maxAge !== undefined))
753
+ throw fail("INVALID_ARGUMENT", "Pinned snapshots do not accept refresh or maxAge.");
754
+ }
755
+ var effectiveCachePolicy = configuration.pipe(Effect4.flatMap((config) => Effect4.try({
756
+ try: () => {
757
+ const policy = config.cache_policy ?? DEFAULT_CACHE_POLICY;
758
+ for (const value of Object.values(policy))
759
+ if (!Number.isSafeInteger(value) || value < 0)
760
+ throw fail("STATE_CORRUPT", "Configured cache durations are invalid.");
761
+ return policy;
762
+ },
763
+ catch: (error) => error
764
+ })));
765
+ function configureCachePolicy(options) {
766
+ return Effect4.gen(function* () {
767
+ yield* Effect4.try({
768
+ try: () => {
769
+ if (options.readMaxAge === undefined && options.catalogMaxAge === undefined)
770
+ throw fail("INVALID_ARGUMENT", "Specify at least one cache duration.");
771
+ for (const value of [options.readMaxAge, options.catalogMaxAge])
772
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 0))
773
+ throw fail("INVALID_ARGUMENT", "Cache durations must be nonnegative integer milliseconds.");
774
+ },
775
+ catch: (error) => error
776
+ });
777
+ const config = yield* configuration;
778
+ const previous = yield* effectiveCachePolicy;
779
+ const next = {
780
+ ...config,
781
+ cache_policy: {
782
+ read_max_age_ms: options.readMaxAge ?? previous.read_max_age_ms,
783
+ catalog_max_age_ms: options.catalogMaxAge ?? previous.catalog_max_age_ms
784
+ }
785
+ };
786
+ yield* (yield* Store).writeJson("config.json", next);
787
+ return { ...publicConfiguration(next), effective_cache_policy: next.cache_policy };
788
+ });
789
+ }
790
+ var clearCachePolicy = Effect4.gen(function* () {
791
+ const { cache_policy: _previous, ...config } = yield* configuration;
792
+ yield* (yield* Store).writeJson("config.json", config);
793
+ return { ...publicConfiguration(config), effective_cache_policy: DEFAULT_CACHE_POLICY };
794
+ });
795
+ var ScopeSchema = Schema3.Struct({ scope: Schema3.String });
796
+ var ObservationSchema = Schema3.Struct({
797
+ page_id: Schema3.String,
798
+ scope: Schema3.String,
799
+ started_at: Schema3.Number,
800
+ validated_at: Schema3.Number,
801
+ snapshot_id: Schema3.optional(Schema3.String),
802
+ invalidated: Schema3.Boolean,
803
+ generation: Schema3.Number
804
+ });
805
+ function freshness(options, validatedAt, now, maxAge) {
806
+ const age = now - validatedAt;
807
+ return {
808
+ policy: options.offline ? "offline" : options.refresh ? "refresh" : options.maxAge !== undefined ? "max_age" : "default",
809
+ validated_at: new Date(validatedAt).toISOString(),
810
+ age_ms: age,
811
+ max_age_ms: maxAge,
812
+ stale: !Number.isFinite(age) || age < 0 || age >= maxAge
813
+ };
814
+ }
815
+ var localIdentity = Effect4.gen(function* () {
816
+ const credential = yield* (yield* Notion).credentialIdentity;
817
+ const keychain = credential === (yield* sha256("ntn-keychain"));
818
+ const key = yield* sha256(JSON.stringify([
819
+ credential,
820
+ process.env.NOTION_WORKSPACE_ID ?? "",
821
+ process.env.NOTION_API_BASE_URL ?? "https://api.notion.com"
822
+ ]));
823
+ return { key, keychain };
824
+ });
825
+ function recordScope(scope) {
826
+ return Effect4.gen(function* () {
827
+ const identity = yield* localIdentity;
828
+ if (!identity.keychain)
829
+ yield* (yield* Store).writeJson(`cache/identities/${identity.key}.json`, { scope });
830
+ });
831
+ }
832
+ function locallySelectedScope(offline = false) {
833
+ return Effect4.gen(function* () {
834
+ const identity = yield* localIdentity;
835
+ if (identity.keychain) {
836
+ if (offline)
837
+ return yield* Effect4.fail(fail("CACHE_SCOPE_UNAVAILABLE", "Official-login identity requires online validation; use an explicitly pinned snapshot offline."));
838
+ return;
839
+ }
840
+ const value = yield* (yield* Store).readJson(`cache/identities/${identity.key}.json`, ScopeSchema);
841
+ if (!value && offline)
842
+ return yield* Effect4.fail(fail("CACHE_SCOPE_UNAVAILABLE", "No locally identifiable cached account scope is available."));
843
+ return value?.scope;
844
+ });
845
+ }
846
+ function validateSnapshot(snapshot) {
847
+ return Effect4.gen(function* () {
848
+ const alias = yield* Effect4.try({
849
+ try: () => aliasFor(snapshot.skill.name),
850
+ catch: () => fail("STATE_CORRUPT", "Snapshot Skill name is invalid.")
851
+ });
852
+ if (snapshot.snapshot_id !== `s_${yield* sha256(JSON.stringify([snapshot.scope, snapshot.skill.id, snapshot.version_id]))}` || alias !== snapshot.skill.alias || snapshot.skill_name !== snapshot.skill.alias || !snapshot.files.some((file) => file.path === "SKILL.md") || new Set(snapshot.files.map((file) => file.path)).size !== snapshot.files.length)
853
+ return yield* Effect4.fail(fail("STATE_CORRUPT", "Snapshot identity or complete file manifest is invalid."));
854
+ const store = yield* Store;
855
+ for (const file of snapshot.files) {
856
+ yield* Effect4.try({
857
+ try: () => {
858
+ if (normalizePath(file.path) !== file.path || !/^[a-f0-9]{64}$/.test(file.sha256) || !Number.isSafeInteger(file.bytes) || file.bytes < 0)
859
+ throw fail("STATE_CORRUPT", "Snapshot file manifest is invalid.");
860
+ },
861
+ catch: () => fail("STATE_CORRUPT", "Snapshot file manifest is invalid.")
862
+ });
863
+ const bytes = yield* store.readBytes(`objects/${file.sha256}`);
864
+ if (bytes.length !== file.bytes || (yield* sha256(bytes)) !== file.sha256)
865
+ return yield* Effect4.fail(fail("STATE_CORRUPT", "A snapshot object failed its content checksum.", {
866
+ path: file.path
867
+ }));
868
+ }
869
+ return snapshot;
870
+ }).pipe(Effect4.mapError((error) => error instanceof SkillsError ? error : fail("STATE_CORRUPT", "Snapshot manifest failed validation.")));
871
+ }
872
+ function publishSnapshotObservation(snapshot, startedAt, generation) {
873
+ return Effect4.gen(function* () {
874
+ yield* validateSnapshot(snapshot);
875
+ const store = yield* Store;
876
+ const validatedAt = yield* Clock.currentTimeMillis;
877
+ const id = yield* (yield* Crypto3.Crypto).randomUUIDv4();
878
+ yield* store.writeJson(`cache/latest/${snapshot.scope}/${snapshot.skill.id}/${id}.json`, {
879
+ page_id: snapshot.skill.id,
880
+ scope: snapshot.scope,
881
+ started_at: startedAt,
882
+ generation,
883
+ validated_at: validatedAt,
884
+ snapshot_id: snapshot.snapshot_id,
885
+ invalidated: false
886
+ });
887
+ yield* recordScope(snapshot.scope);
888
+ return {
889
+ ...snapshot,
890
+ source: "notion",
891
+ freshness: freshness({ refresh: true }, validatedAt, validatedAt, (yield* effectiveCachePolicy).read_max_age_ms)
892
+ };
893
+ }).pipe(Effect4.mapError((error) => error instanceof SkillsError ? error : fail("CRYPTO_ERROR", "Could not publish the observation identity.")));
894
+ }
895
+ function cachedRemoteObservation(page, scope) {
896
+ return Effect4.gen(function* () {
897
+ const store = yield* Store;
898
+ const keys = yield* store.listKeys(`cache/latest/${scope}/${page}`);
899
+ const entries = [];
900
+ for (const key of keys) {
901
+ if (!key.endsWith(".json"))
902
+ continue;
903
+ const entry = yield* store.readJson(key, ObservationSchema);
904
+ if (entry) {
905
+ if (entry.scope !== scope || entry.page_id !== page || !Number.isFinite(entry.validated_at) || !Number.isFinite(entry.started_at) || !Number.isSafeInteger(entry.generation) || entry.generation < 1)
906
+ return yield* Effect4.fail(fail("STATE_CORRUPT", "Cache observation scope or timestamp is invalid."));
907
+ entries.push(entry);
908
+ }
909
+ }
910
+ entries.sort((a, b) => b.generation - a.generation);
911
+ const latest = entries[0];
912
+ if (!latest || latest.invalidated)
913
+ return;
914
+ if (!latest.snapshot_id || !/^s_[a-f0-9]{64}$/.test(latest.snapshot_id))
915
+ return yield* Effect4.fail(fail("STATE_CORRUPT", "Latest observation has no valid snapshot identity."));
916
+ const snapshot = yield* store.readJson(`snapshots/${latest.snapshot_id}.json`, SnapshotSchema);
917
+ if (!snapshot || snapshot.scope !== scope || snapshot.skill.id !== page)
918
+ return yield* Effect4.fail(fail("STATE_CORRUPT", "Latest observation points to a missing or foreign snapshot."));
919
+ yield* validateSnapshot(snapshot);
920
+ return { snapshot, validated_at: latest.validated_at };
921
+ });
922
+ }
923
+ function invalidateSnapshotCache(page, scope) {
924
+ return Effect4.gen(function* () {
925
+ const store = yield* Store;
926
+ const scopes = scope ? [scope] : [...new Set((yield* store.listKeys("cache/latest")).map((key) => key.split("/")[2]))];
927
+ const now = yield* Clock.currentTimeMillis;
928
+ for (const selected of scopes) {
929
+ const generation = yield* store.reserveCacheGeneration(selected, page);
930
+ const id = yield* (yield* Crypto3.Crypto).randomUUIDv4();
931
+ yield* store.writeJson(`cache/latest/${selected}/${page}/${id}.json`, {
932
+ page_id: page,
933
+ scope: selected,
934
+ started_at: now,
935
+ validated_at: now,
936
+ generation,
937
+ invalidated: true
938
+ });
939
+ }
940
+ }).pipe(Effect4.mapError((error) => error instanceof SkillsError ? error : fail("CRYPTO_ERROR", "Could not invalidate the observation identity.")));
941
+ }
942
+ function cachedTarget(target, database) {
943
+ return Effect4.gen(function* () {
944
+ const parsed = yield* Effect4.try({
945
+ try: () => parseTarget(target),
946
+ catch: (error) => error
947
+ });
948
+ if (parsed.snapshot)
949
+ return yield* Effect4.fail(fail("INVALID_ARGUMENT", "Cache operations require a current target."));
950
+ const scope = yield* locallySelectedScope(true);
951
+ const config = yield* configuration;
952
+ const matches = config.sources?.filter((source) => source.alias === database) ?? [];
953
+ if (database !== undefined && !pageId(database) && new Set(matches.map((source) => source.database_id)).size > 1)
954
+ return yield* Effect4.fail(fail("DATABASE_AMBIGUOUS", "Registered database alias is ambiguous."));
955
+ const selectedDatabase = database === undefined ? undefined : pageId(database) ?? matches[0]?.database_id;
956
+ if (database !== undefined && !selectedDatabase)
957
+ return yield* Effect4.fail(fail("DATABASE_NOT_FOUND", "No registered database matched the selector."));
958
+ const store = yield* Store;
959
+ const id = pageId(parsed.selector);
960
+ if (id) {
961
+ const observed = yield* cachedRemoteObservation(id, scope);
962
+ if (selectedDatabase && observed && observed.snapshot.skill.database_id !== selectedDatabase)
963
+ return yield* Effect4.fail(fail("SKILL_NOT_FOUND", "Target is outside the selected database."));
964
+ return { page: id, scope };
965
+ }
966
+ const key = `cache/catalogs/${scope}/${yield* sha256(JSON.stringify(["database-selection-v2", database ?? "auto", config.sources ?? []]))}.json`;
967
+ const catalog = yield* store.readJson(key, CatalogSchema);
968
+ if (!catalog || catalog.scope !== scope || catalog.coverage.failed_sources.length)
969
+ return yield* Effect4.fail(fail("CACHE_MISSING", "A complete catalog for this exact scope and database selection is required."));
970
+ const skill = yield* Effect4.try({
971
+ try: () => resolveSkill(parsed.selector, catalog, selectedDatabase),
972
+ catch: (error) => error
973
+ });
974
+ return { page: skill.id, scope };
975
+ });
976
+ }
977
+ function cacheStatus(target, options = {}) {
978
+ return Effect4.gen(function* () {
979
+ const store = yield* Store;
980
+ const selected = target === undefined ? undefined : yield* cachedTarget(target, options.database);
981
+ const keys = yield* store.listKeys("cache");
982
+ const pairs = new Map;
983
+ for (const key of keys) {
984
+ const parts = key.split("/");
985
+ if (parts[1] === "latest" && (!selected || parts[2] === selected.scope && parts[3] === selected.page))
986
+ pairs.set(`${parts[2]}/${parts[3]}`, { scope: parts[2], page: parts[3] });
987
+ }
988
+ const now = yield* Clock.currentTimeMillis;
989
+ const policy = yield* effectiveCachePolicy;
990
+ const observations = [];
991
+ for (const pair of pairs.values()) {
992
+ const observation = yield* cachedRemoteObservation(pair.page, pair.scope);
993
+ if (observation)
994
+ observations.push({
995
+ scope: pair.scope,
996
+ page_id: pair.page,
997
+ snapshot_id: observation.snapshot.snapshot_id,
998
+ version_id: observation.snapshot.version_id,
999
+ source: "local_cache",
1000
+ freshness: freshness({}, observation.validated_at, now, policy.read_max_age_ms)
1001
+ });
1002
+ }
1003
+ const catalogs = [];
1004
+ for (const key of keys) {
1005
+ if (!key.startsWith("cache/catalogs/") || !key.endsWith(".json"))
1006
+ continue;
1007
+ const value = yield* store.readJson(key, CatalogSchema);
1008
+ if (value && (!selected || value.scope === selected.scope && value.skills.some((skill) => skill.id === selected.page)))
1009
+ catalogs.push({
1010
+ scope: value.scope,
1011
+ fetched_at: value.fetched_at,
1012
+ coverage: value.coverage,
1013
+ freshness: freshness({}, value.fetched_at, now, policy.catalog_max_age_ms)
1014
+ });
1015
+ }
1016
+ return {
1017
+ config_directory: store.configRoot,
1018
+ state_directory: store.root,
1019
+ cache_directory: store.cacheRoot,
1020
+ effective_cache_policy: policy,
1021
+ scopes: [
1022
+ ...new Set(keys.filter((key) => /cache\/(latest|catalogs)\//.test(key)).map((key) => key.split("/")[2]))
1023
+ ],
1024
+ observations,
1025
+ catalogs
1026
+ };
1027
+ });
1028
+ }
1029
+ function clearCache(target, options = {}) {
1030
+ return Effect4.gen(function* () {
1031
+ if (Number(target !== undefined) + Number(Boolean(options.all)) !== 1 || options.all && options.database !== undefined)
1032
+ return yield* Effect4.fail(fail("INVALID_ARGUMENT", "Specify exactly one current target or all; database requires a target."));
1033
+ const store = yield* Store;
1034
+ const selected = options.all ? undefined : yield* cachedTarget(target, options.database);
1035
+ const keys = [];
1036
+ for (const key of yield* store.listKeys("cache")) {
1037
+ if (!selected) {
1038
+ keys.push(key);
1039
+ continue;
1040
+ }
1041
+ if (key.startsWith(`cache/latest/${selected.scope}/${selected.page}/`))
1042
+ keys.push(key);
1043
+ else if (key.startsWith(`cache/catalogs/${selected.scope}/`) && key.endsWith(".json")) {
1044
+ const value = yield* store.readJson(key, CatalogSchema);
1045
+ if (!value || value.skills.some((skill) => skill.id === selected.page) || value.coverage.failed_sources.length || !value.coverage.exhaustive)
1046
+ keys.push(key);
1047
+ }
1048
+ }
1049
+ for (const key of yield* store.listKeys("cache-generations")) {
1050
+ const parts = key.split("/");
1051
+ const scope = parts[1];
1052
+ const identity = parts[2].replace(/\.json$/, "");
1053
+ if (selected && scope !== selected.scope)
1054
+ continue;
1055
+ if (identity.startsWith("catalog-")) {
1056
+ if (!selected || keys.some((entry) => entry === `cache/catalogs/${scope}/${identity.slice(8)}.json`) || !(yield* store.readJson(`cache/catalogs/${scope}/${identity.slice(8)}.json`, CatalogSchema)))
1057
+ keys.push(`cache/catalogs/${scope}/${identity.slice(8)}.json`);
1058
+ } else if (!selected || identity === selected.page)
1059
+ keys.push(`cache/latest/${scope}/${identity}/.fence`);
1060
+ }
1061
+ const entries = [...new Set(keys)];
1062
+ const retired = options.dryRun ? [] : yield* store.retireKeys(entries);
1063
+ return { operation: "cache_clear", dry_run: Boolean(options.dryRun), entries, retired };
1064
+ });
1065
+ }
1066
+
1067
+ // packages/core/src/catalog.ts
1068
+ var authScope = Effect5.gen(function* () {
462
1069
  const api = yield* Notion;
463
1070
  const value = yield* api.request("v1/users/me");
464
- const user = yield* Effect3.try({
1071
+ const user = yield* Effect5.try({
465
1072
  try: () => decode(UserSchema, value),
466
1073
  catch: () => fail("INVALID_RESPONSE", "Invalid authenticated user response.")
467
1074
  });
468
1075
  const credential = yield* api.credentialIdentity;
469
- return yield* sha256(JSON.stringify([
1076
+ const scope = yield* sha256(JSON.stringify([
470
1077
  user.id,
471
1078
  process.env.NOTION_WORKSPACE_ID ?? "",
472
1079
  process.env.NOTION_API_BASE_URL ?? "https://api.notion.com",
473
1080
  credential
474
1081
  ]));
1082
+ return scope;
475
1083
  });
476
1084
  function paginate(path, item, initial) {
477
- return Effect3.gen(function* () {
1085
+ return Effect5.gen(function* () {
478
1086
  const api = yield* Notion;
479
1087
  const items = [];
480
1088
  const cursors = new Set;
@@ -485,7 +1093,7 @@ function paginate(path, item, initial) {
485
1093
  page_size: 100,
486
1094
  ...cursor ? { start_cursor: cursor } : {}
487
1095
  });
488
- const page = yield* Effect3.try({
1096
+ const page = yield* Effect5.try({
489
1097
  try: () => decode(listSchema(item), value),
490
1098
  catch: () => fail("INVALID_RESPONSE", "Invalid paginated Notion response.", { path })
491
1099
  });
@@ -493,46 +1101,56 @@ function paginate(path, item, initial) {
493
1101
  if (!page.has_more)
494
1102
  return items;
495
1103
  if (!page.next_cursor || cursors.has(page.next_cursor))
496
- return yield* Effect3.fail(fail("INVALID_RESPONSE", "Notion returned a missing or repeating cursor.", { path }));
1104
+ return yield* Effect5.fail(fail("INVALID_RESPONSE", "Notion returned a missing or repeating cursor.", { path }));
497
1105
  cursors.add(page.next_cursor);
498
1106
  cursor = page.next_cursor;
499
1107
  }
500
1108
  });
501
1109
  }
502
1110
  function databaseId(input, sources) {
503
- return Effect3.gen(function* () {
1111
+ return Effect5.gen(function* () {
504
1112
  const id = pageId(input);
505
1113
  if (id)
506
1114
  return id;
507
1115
  const configured = sources ?? (yield* configuredSources);
508
1116
  const matches = configured.filter((source) => source.alias === input);
509
1117
  if (!matches.length)
510
- return yield* Effect3.fail(fail("DATABASE_NOT_FOUND", "No registered database alias matched; use an ID, URL or exact registered alias.", { selector: input, candidates: configured }));
1118
+ return yield* Effect5.fail(fail("DATABASE_NOT_FOUND", "No registered database alias matched; use an ID, URL or exact registered alias.", { selector: input, candidates: configured }));
511
1119
  if (matches.some((source) => source.database_id !== matches[0].database_id))
512
- return yield* Effect3.fail(fail("DATABASE_AMBIGUOUS", "The registered alias names multiple databases; use a database ID.", { selector: input, candidates: matches }));
1120
+ return yield* Effect5.fail(fail("DATABASE_AMBIGUOUS", "The registered alias names multiple databases; use a database ID.", { selector: input, candidates: matches }));
513
1121
  return matches[0].database_id;
514
1122
  });
515
1123
  }
516
1124
  function explicitSource(input, sources) {
517
- return Effect3.gen(function* () {
1125
+ return Effect5.gen(function* () {
518
1126
  const configured = sources ?? (yield* configuredSources);
519
1127
  const id = yield* databaseId(input, configured);
520
1128
  const registered = configured.find((source) => source.database_id === id);
521
1129
  const api = yield* Notion;
522
- const db = yield* Effect3.gen(function* () {
1130
+ const db = yield* Effect5.gen(function* () {
523
1131
  const value = yield* api.request(`v1/databases/${id}`);
524
- return yield* Effect3.try({
1132
+ return yield* Effect5.try({
525
1133
  try: () => decode(DatabaseSchema, value),
526
1134
  catch: () => fail("INVALID_RESPONSE", "Invalid database response.")
527
1135
  });
528
- }).pipe(Effect3.mapError((error) => fail(error.code, error.message, {
1136
+ }).pipe(Effect5.mapError((error) => fail(error.code, error.message, {
529
1137
  ...property(error.details),
530
1138
  database_id: id,
531
1139
  alias: registered?.alias ?? id,
532
1140
  ...registered ? { title: registered.title } : {}
533
1141
  })));
534
- if (db.database_type !== "skills" || db.in_trash)
535
- return yield* Effect3.fail(fail("NOT_SKILLS_DATABASE", "Only a non-trashed database_type=skills database can be consumed.", { database_id: id, alias: registered?.alias ?? id, title: text(db.title) }));
1142
+ let referencesDatabase = false;
1143
+ if (db.database_type !== "skills" && !db.in_trash) {
1144
+ referencesDatabase = db.data_sources.length > 0;
1145
+ for (const source of db.data_sources) {
1146
+ const raw = yield* api.request(`v1/data_sources/${source.id}`);
1147
+ const props = property(property(raw).properties);
1148
+ if (property(props.References).type !== "rich_text" || property(props.Description).type !== "rich_text")
1149
+ referencesDatabase = false;
1150
+ }
1151
+ }
1152
+ if (db.in_trash || db.database_type !== "skills" && !referencesDatabase)
1153
+ return yield* Effect5.fail(fail("NOT_SKILLS_DATABASE", "A skill database needs rich-text Description and References properties, or the native Skills type.", { database_id: id, alias: registered?.alias ?? id, title: text(db.title) }));
536
1154
  return {
537
1155
  alias: registered?.alias ?? id,
538
1156
  database_id: id,
@@ -542,14 +1160,15 @@ function explicitSource(input, sources) {
542
1160
  });
543
1161
  }
544
1162
  function discoverDatabases() {
545
- return Effect3.gen(function* () {
1163
+ return Effect5.gen(function* () {
546
1164
  const databases = new Map;
547
1165
  const failures = [];
548
1166
  const sources = yield* paginate("v1/search", DataSourceSchema, {
549
1167
  filter: { property: "object", value: "data_source" }
550
1168
  });
551
1169
  for (const source of sources) {
552
- if (source.database_type !== "skills" || source.in_trash)
1170
+ const props = property(source.properties);
1171
+ if (source.in_trash || source.database_type !== "skills" && (property(props.References).type !== "rich_text" || property(props.Description).type !== "rich_text"))
553
1172
  continue;
554
1173
  const id = source.parent.database_id;
555
1174
  const previous = databases.get(id);
@@ -562,7 +1181,7 @@ function discoverDatabases() {
562
1181
  }
563
1182
  const configured = yield* configuredSources;
564
1183
  for (const source of configured) {
565
- const result = yield* explicitSource(source.database_id, configured).pipe(Effect3.result);
1184
+ const result = yield* explicitSource(source.database_id, configured).pipe(Effect5.result);
566
1185
  if (result._tag === "Failure")
567
1186
  failures.push({
568
1187
  id: source.database_id,
@@ -578,7 +1197,7 @@ function discoverDatabases() {
578
1197
  });
579
1198
  }
580
1199
  function creationSource(database) {
581
- return Effect3.gen(function* () {
1200
+ return Effect5.gen(function* () {
582
1201
  if (database !== undefined)
583
1202
  return yield* explicitSource(database);
584
1203
  const config = yield* configuration;
@@ -586,14 +1205,14 @@ function creationSource(database) {
586
1205
  return yield* explicitSource(config.default_database);
587
1206
  const discovered = yield* discoverDatabases();
588
1207
  if (discovered.failures.length)
589
- return yield* Effect3.fail(fail("CATALOG_INCOMPLETE", "Database discovery failed; specify --database or configure a default.", discovered));
1208
+ return yield* Effect5.fail(fail("CATALOG_INCOMPLETE", "Database discovery failed; specify --database or configure a default.", discovered));
590
1209
  if (discovered.databases.length !== 1)
591
- return yield* Effect3.fail(fail(discovered.databases.length ? "DATABASE_AMBIGUOUS" : "DATABASE_NOT_FOUND", "Create requires one discovered Skills Database, a configured default, or --database.", { candidates: discovered.databases }));
1210
+ return yield* Effect5.fail(fail(discovered.databases.length ? "DATABASE_AMBIGUOUS" : "DATABASE_NOT_FOUND", "Create requires one discovered Skills Database, a configured default, or --database.", { candidates: discovered.databases }));
592
1211
  return yield* explicitSource(discovered.databases[0].database_id);
593
1212
  });
594
1213
  }
595
1214
  function setDefaultDatabase(database) {
596
- return Effect3.gen(function* () {
1215
+ return Effect5.gen(function* () {
597
1216
  const config = yield* configuration;
598
1217
  const source = database === undefined ? undefined : yield* explicitSource(database);
599
1218
  const { default_database: _previous, ...rest } = config;
@@ -604,27 +1223,48 @@ function setDefaultDatabase(database) {
604
1223
  });
605
1224
  }
606
1225
  function catalog(options = {}) {
607
- return Effect3.gen(function* () {
608
- const scope = yield* authScope;
1226
+ return Effect5.gen(function* () {
1227
+ yield* Effect5.try({
1228
+ try: () => validateReadPolicy(options),
1229
+ catch: (error) => error
1230
+ });
1231
+ const selectedScope = !options.refresh ? yield* locallySelectedScope(Boolean(options.offline)) : undefined;
1232
+ const scope = selectedScope ?? (yield* authScope);
609
1233
  const store = yield* Store;
610
1234
  const configured = yield* configuredSources;
611
- const key = `catalogs/${scope}/${yield* sha256(JSON.stringify(["database-selection-v1", options.database ?? "auto", configured]))}.json`;
612
- const now = yield* Clock.currentTimeMillis;
1235
+ const key = `cache/catalogs/${scope}/${yield* sha256(JSON.stringify(["database-selection-v2", options.database ?? "auto", configured]))}.json`;
1236
+ const now = yield* Clock2.currentTimeMillis;
1237
+ const maxAge = options.maxAge ?? (yield* effectiveCachePolicy).catalog_max_age_ms;
613
1238
  if (!options.refresh) {
614
- const cached = yield* store.readJson(key, CatalogSchema);
615
- if (cached && now - cached.fetched_at < 60000 && !cached.coverage.failed_sources.length) {
1239
+ const result = yield* store.readJson(key, CatalogSchema).pipe(Effect5.result);
1240
+ if (result._tag === "Failure" && options.offline)
1241
+ return yield* Effect5.fail(result.failure);
1242
+ const cached = result._tag === "Success" ? result.success : undefined;
1243
+ const age = cached ? now - cached.fetched_at : NaN;
1244
+ if (cached && cached.scope === scope && !cached.coverage.failed_sources.length && (options.offline || Number.isFinite(age) && age >= 0 && age < maxAge)) {
616
1245
  for (const skill of cached.skills) {
617
- yield* Effect3.try({
1246
+ yield* Effect5.try({
618
1247
  try: () => {
619
1248
  if (aliasFor(skill.name) !== skill.alias)
620
1249
  throw fail("INVALID_SKILL_NAME", "Cached skill name differs from its Notion Name.", { page_id: skill.id, name: skill.name });
621
1250
  },
622
- catch: (error) => error instanceof SkillsError ? fail(error.code, error.message, { page_id: skill.id, name: skill.name }) : error
1251
+ catch: (error) => error instanceof SkillsError ? fail(error.code, error.message, { page_id: skill.id, name: skill.name }) : fail("STATE_CORRUPT", "Cached Skill title failed validation.", {
1252
+ page_id: skill.id
1253
+ })
623
1254
  });
624
1255
  }
625
- return cached;
1256
+ return {
1257
+ ...cached,
1258
+ source: "local_cache",
1259
+ freshness: freshness(options, cached.fetched_at, now, maxAge)
1260
+ };
626
1261
  }
1262
+ if (options.offline)
1263
+ return yield* Effect5.fail(fail("CACHE_MISSING", "No complete catalog observation is available for the selected scope."));
627
1264
  }
1265
+ const validatedScope = selectedScope ? yield* authScope : scope;
1266
+ const catalogIdentity = yield* sha256(JSON.stringify(["database-selection-v2", options.database ?? "auto", configured]));
1267
+ const catalogGeneration = yield* store.reserveCacheGeneration(validatedScope, `catalog-${catalogIdentity}`);
628
1268
  const databases = new Map;
629
1269
  const failures = [];
630
1270
  if (options.database !== undefined) {
@@ -640,7 +1280,7 @@ function catalog(options = {}) {
640
1280
  const queried = [];
641
1281
  for (const db of databases.values()) {
642
1282
  for (const id of new Set(db.data_source_ids)) {
643
- const result = yield* paginate(`v1/data_sources/${id}/query`, PageSchema, {}).pipe(Effect3.result);
1283
+ const result = yield* paginate(`v1/data_sources/${id}/query`, PageSchema, {}).pipe(Effect5.result);
644
1284
  if (result._tag === "Failure") {
645
1285
  failures.push({
646
1286
  id,
@@ -656,7 +1296,7 @@ function catalog(options = {}) {
656
1296
  for (const row of result.success) {
657
1297
  if (row.in_trash)
658
1298
  continue;
659
- const skill = yield* Effect3.try({
1299
+ const skill = yield* Effect5.try({
660
1300
  try: () => skillFromPage(row, db, id),
661
1301
  catch: (e) => e
662
1302
  });
@@ -665,8 +1305,8 @@ function catalog(options = {}) {
665
1305
  }
666
1306
  }
667
1307
  const output = {
668
- scope,
669
- fetched_at: now,
1308
+ scope: validatedScope,
1309
+ fetched_at: yield* Clock2.currentTimeMillis,
670
1310
  databases: [...databases.values()],
671
1311
  skills: [...skills.values()].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id)),
672
1312
  coverage: {
@@ -677,20 +1317,26 @@ function catalog(options = {}) {
677
1317
  search_index_limited: options.database === undefined
678
1318
  }
679
1319
  };
680
- yield* store.writeJson(key, output);
681
- return output;
1320
+ const validatedKey = `cache/catalogs/${validatedScope}/${catalogIdentity}.json`;
1321
+ yield* store.writeJson(validatedKey, { ...output, generation: catalogGeneration });
1322
+ yield* recordScope(validatedScope);
1323
+ return {
1324
+ ...output,
1325
+ source: "notion",
1326
+ freshness: freshness(options, output.fetched_at, output.fetched_at, maxAge)
1327
+ };
682
1328
  });
683
1329
  }
684
1330
  function addSource(alias, input) {
685
- return Effect3.gen(function* () {
1331
+ return Effect5.gen(function* () {
686
1332
  if (!alias.trim())
687
- return yield* Effect3.fail(fail("INVALID_SOURCE", "Source alias must not be empty."));
1333
+ return yield* Effect5.fail(fail("INVALID_SOURCE", "Source alias must not be empty."));
688
1334
  const source = { ...yield* explicitSource(input), alias };
689
1335
  const config = yield* configuration;
690
1336
  const configured = config.sources ?? [];
691
1337
  const sameAlias = configured.find((s) => s.alias === alias);
692
1338
  if (sameAlias && sameAlias.database_id !== source.database_id)
693
- return yield* Effect3.fail(fail("SOURCE_AMBIGUOUS", "This alias already names another database.", { alias }));
1339
+ return yield* Effect5.fail(fail("SOURCE_AMBIGUOUS", "This alias already names another database.", { alias }));
694
1340
  const sources = configured.filter((s) => s.database_id !== source.database_id);
695
1341
  sources.push(source);
696
1342
  const store = yield* Store;
@@ -699,8 +1345,8 @@ function addSource(alias, input) {
699
1345
  });
700
1346
  }
701
1347
  // packages/core/src/snapshot.ts
702
- import { Clock as Clock2, Effect as Effect5, Stream as Stream2 } from "effect";
703
- import { HttpClient } from "effect/http";
1348
+ import { Clock as Clock3, Effect as Effect8, Stream as Stream2 } from "effect";
1349
+ import { HttpClient as HttpClient2 } from "effect/http";
704
1350
 
705
1351
  // node_modules/.bun/fflate@0.8.3/node_modules/fflate/esm/index.mjs
706
1352
  import { createRequire } from "module";
@@ -1805,7 +2451,7 @@ function readArchive(compressed) {
1805
2451
  }
1806
2452
 
1807
2453
  // packages/core/src/import.ts
1808
- import { Effect as Effect4, FileSystem as FileSystem2, Path as Path2 } from "effect";
2454
+ import { Effect as Effect6, FileSystem as FileSystem2, Path as Path2 } from "effect";
1809
2455
  import { parse as parse2 } from "effect/encoding/Yaml";
1810
2456
  var MAX_BYTES = 128 * 1024 * 1024;
1811
2457
  var MAX_FILES = 1e4;
@@ -1942,7 +2588,7 @@ function importFiles(input, single = false) {
1942
2588
  return files;
1943
2589
  }
1944
2590
  function loadImport(input) {
1945
- return Effect4.gen(function* () {
2591
+ return Effect6.gen(function* () {
1946
2592
  const fs = yield* FileSystem2.FileSystem;
1947
2593
  const path = yield* Path2.Path;
1948
2594
  const full = path.resolve(input);
@@ -1951,45 +2597,45 @@ function loadImport(input) {
1951
2597
  if (info.type === "Directory") {
1952
2598
  const names = yield* fs.readDirectory(full, { recursive: true });
1953
2599
  if (names.length > MAX_FILES)
1954
- return yield* Effect4.fail(fail("ARCHIVE_TOO_LARGE", "Directory contains too many entries."));
2600
+ return yield* Effect6.fail(fail("ARCHIVE_TOO_LARGE", "Directory contains too many entries."));
1955
2601
  let total = 0;
1956
2602
  for (const name of names.sort()) {
1957
2603
  const stat = yield* fs.stat(path.join(full, name));
1958
2604
  if (stat.type === "Directory")
1959
2605
  continue;
1960
2606
  if (stat.type !== "File")
1961
- return yield* Effect4.fail(fail("INVALID_INPUT", "Import accepts only regular files and directories.", {
2607
+ return yield* Effect6.fail(fail("INVALID_INPUT", "Import accepts only regular files and directories.", {
1962
2608
  path: name
1963
2609
  }));
1964
2610
  const size = Number(stat.size);
1965
2611
  if (total + size > MAX_BYTES)
1966
- return yield* Effect4.fail(fail("ARCHIVE_TOO_LARGE", "Directory exceeds 128 MiB."));
2612
+ return yield* Effect6.fail(fail("ARCHIVE_TOO_LARGE", "Directory exceeds 128 MiB."));
1967
2613
  const bytes = yield* fs.readFile(path.join(full, name));
1968
2614
  total += bytes.length;
1969
2615
  if (total > MAX_BYTES)
1970
- return yield* Effect4.fail(fail("ARCHIVE_TOO_LARGE", "Directory exceeds 128 MiB."));
2616
+ return yield* Effect6.fail(fail("ARCHIVE_TOO_LARGE", "Directory exceeds 128 MiB."));
1971
2617
  files.push({ path: normalizePath(name.split(path.sep).join("/")), bytes });
1972
2618
  }
1973
2619
  return { kind: "directory", files };
1974
2620
  }
1975
2621
  if (info.type !== "File")
1976
- return yield* Effect4.fail(fail("INVALID_INPUT", "Import requires a ZIP file, directory or Markdown file."));
2622
+ return yield* Effect6.fail(fail("INVALID_INPUT", "Import requires a ZIP file, directory or Markdown file."));
1977
2623
  const zip = /\.zip$/i.test(full);
1978
2624
  if (!zip && !/\.(md|markdown)$/i.test(full))
1979
- return yield* Effect4.fail(fail("INVALID_INPUT", "Import file must be .zip, .md or .markdown."));
2625
+ return yield* Effect6.fail(fail("INVALID_INPUT", "Import file must be .zip, .md or .markdown."));
1980
2626
  if (Number(info.size) > (zip ? 32 * 1024 * 1024 : MAX_BYTES))
1981
- return yield* Effect4.fail(fail("ARCHIVE_TOO_LARGE", "Import input exceeds its size limit."));
2627
+ return yield* Effect6.fail(fail("ARCHIVE_TOO_LARGE", "Import input exceeds its size limit."));
1982
2628
  const bytes = yield* fs.readFile(full);
1983
2629
  if (bytes.length > (zip ? 32 * 1024 * 1024 : MAX_BYTES))
1984
- return yield* Effect4.fail(fail("ARCHIVE_TOO_LARGE", "Import input exceeds its size limit."));
2630
+ return yield* Effect6.fail(fail("ARCHIVE_TOO_LARGE", "Import input exceeds its size limit."));
1985
2631
  return zip ? {
1986
2632
  kind: "zip",
1987
- files: yield* Effect4.try({
2633
+ files: yield* Effect6.try({
1988
2634
  try: () => readImportZip(bytes),
1989
2635
  catch: (e) => e
1990
2636
  })
1991
2637
  } : { kind: "markdown", files: [{ path: path.basename(full), bytes }] };
1992
- }).pipe(Effect4.mapError((error) => error instanceof SkillsError ? error : fail("INPUT_FAILED", "Could not read the import input.", { input })));
2638
+ }).pipe(Effect6.mapError((error) => error instanceof SkillsError ? error : fail("INPUT_FAILED", "Could not read the import input.", { input })));
1993
2639
  }
1994
2640
 
1995
2641
  // packages/core/src/portable.ts
@@ -2086,7 +2732,7 @@ function readPortable(input) {
2086
2732
  throw fail("INVALID_ARCHIVE", "Portable entrypoint is missing.");
2087
2733
  const rawProjection = manifest.projection;
2088
2734
  const projection = property(rawProjection);
2089
- if (rawProjection !== undefined && (typeof projection.name !== "string" || typeof projection.description !== "string" || typeof projection.body !== "string"))
2735
+ if (rawProjection !== undefined && (typeof projection.name !== "string" || typeof projection.description !== "string" || typeof projection.body !== "string" || projection.references !== undefined && (typeof projection.references !== "object" || projection.references === null || Array.isArray(projection.references) || Object.values(projection.references).some((value) => typeof value !== "string"))))
2090
2736
  throw fail("INVALID_ARCHIVE", "Invalid portable projection.");
2091
2737
  return {
2092
2738
  name: manifest.name,
@@ -2127,24 +2773,275 @@ ${body.trim()}${body.trim() ? `
2127
2773
  };
2128
2774
  }
2129
2775
 
2776
+ // packages/core/src/references.ts
2777
+ import { Effect as Effect7 } from "effect";
2778
+ import { HttpClient } from "effect/http";
2779
+ function referencesProperty(raw) {
2780
+ const value = property(property(raw).properties).References;
2781
+ if (value === undefined)
2782
+ return;
2783
+ const reference = property(value);
2784
+ if (reference.type !== "rich_text" || typeof reference.id !== "string")
2785
+ throw fail("INVALID_REFERENCES", "References must be a rich-text property containing page mentions or links.");
2786
+ return reference;
2787
+ }
2788
+ function pageMarkdown(raw) {
2789
+ const value = property(raw);
2790
+ if (value.object !== "page_markdown" || typeof value.markdown !== "string" || value.truncated !== false || !Array.isArray(value.unknown_block_ids) || value.unknown_block_ids.length)
2791
+ throw fail("MARKDOWN_INCOMPLETE", "Cannot read or write truncated or unsupported page Markdown.");
2792
+ return value.markdown;
2793
+ }
2794
+ function referencePath(title) {
2795
+ const label = title.trim();
2796
+ const candidate = /\.md$/i.test(label) ? label.startsWith("references/") ? label : `references/${label}` : `references/${label.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-|-$/g, "")}.md`;
2797
+ if (normalizePath(candidate) !== candidate || candidate === "references/.md" || !candidate.startsWith("references/"))
2798
+ throw fail("INVALID_REFERENCES", "Reference titles must identify a safe Markdown path.", {
2799
+ title
2800
+ });
2801
+ return candidate;
2802
+ }
2803
+ function relativePath(from, to) {
2804
+ const base = from.split("/").slice(0, -1);
2805
+ const target = to.split("/");
2806
+ while (base.length && base[0] === target[0]) {
2807
+ base.shift();
2808
+ target.shift();
2809
+ }
2810
+ const value = [...base.map(() => ".."), ...target].join("/");
2811
+ return value.startsWith(".") ? value : `./${value}`;
2812
+ }
2813
+ function rewritePageLinks(markdown, from, pages, direction) {
2814
+ const byId = new Map(pages.map((page) => [page.id, page.path]));
2815
+ const byPath = new Map(pages.map((page) => [page.path, page.id]));
2816
+ const destination = (value) => {
2817
+ if (direction === "local") {
2818
+ const id = pageId(value);
2819
+ const target = id && byId.get(id);
2820
+ if (!target)
2821
+ return value;
2822
+ const hash = new URL(value).hash;
2823
+ return relativePath(from, target).split("/").map((part) => encodeURIComponent(part)).join("/") + hash;
2824
+ }
2825
+ if (/^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(value))
2826
+ return value;
2827
+ const match = /^([^?#]+)([?#].*)?$/.exec(value);
2828
+ if (!match)
2829
+ return value;
2830
+ let target;
2831
+ try {
2832
+ target = normalizePath(decodeURIComponent(match[1]), from);
2833
+ } catch {
2834
+ return value;
2835
+ }
2836
+ const id = byPath.get(target);
2837
+ return id ? `https://www.notion.so/${id.replaceAll("-", "")}${match[2]?.startsWith("#") ? match[2] : ""}` : value;
2838
+ };
2839
+ let fence;
2840
+ return markdown.split(`
2841
+ `).map((line) => {
2842
+ const marker = /^\s*(`{3,}|~{3,})/.exec(line);
2843
+ if (fence) {
2844
+ if (marker && marker[1][0] === fence.marker && marker[1].length >= fence.length)
2845
+ fence = undefined;
2846
+ return line;
2847
+ }
2848
+ if (marker) {
2849
+ fence = { marker: marker[1][0], length: marker[1].length };
2850
+ return line;
2851
+ }
2852
+ return line.split(/(`+[^`]*`+)/g).map((part, index) => {
2853
+ if (index % 2)
2854
+ return part;
2855
+ let output = part.replace(/<(?:mention-page|page)\b[^>]*\burl="([^"]+)"[^>]*>([\s\S]*?)<\/(?:mention-page|page)>/g, (all, url, title) => {
2856
+ const changed = destination(url);
2857
+ return changed === url ? all : `[${title}](${changed})`;
2858
+ });
2859
+ output = output.replace(/(\]\(\s*<?)([^\s)>]+)(>?)(?=\s|\))/g, (_all, start, url, end) => `${start}${destination(url)}${end}`);
2860
+ output = output.replace(/(^\s*\[[^\]]+\]:\s*<?)([^\s>]+)(>?)/g, (_all, start, url, end) => `${start}${destination(url)}${end}`);
2861
+ if (direction === "local")
2862
+ output = output.replace(/https?:\/\/[^\s<>\)\]]+/g, (url) => destination(url));
2863
+ return output;
2864
+ }).join("");
2865
+ }).join(`
2866
+ `);
2867
+ }
2868
+ function childPageTags(markdown) {
2869
+ return [...markdown.matchAll(/<page\b[^>]*\burl="[^"]+"[^>]*>[\s\S]*?<\/page>/g)].map((match) => match[0]);
2870
+ }
2871
+ function withoutChildPages(markdown) {
2872
+ return markdown.replace(/<page\b[^>]*\burl="[^"]+"[^>]*>[\s\S]*?<\/page>/g, "").trim();
2873
+ }
2874
+ function propertyEntries(page, reference) {
2875
+ return Effect7.gen(function* () {
2876
+ const api = yield* Notion;
2877
+ const items = [];
2878
+ let cursor;
2879
+ const seen = new Set;
2880
+ do {
2881
+ const raw = property(yield* api.request(`v1/pages/${property(page).id}/properties/${reference.id}?page_size=100${cursor ? `&start_cursor=${encodeURIComponent(cursor)}` : ""}`));
2882
+ if (raw.object === "property_item")
2883
+ return [raw.rich_text];
2884
+ if (!Array.isArray(raw.results) || typeof raw.has_more !== "boolean")
2885
+ return yield* Effect7.fail(fail("INVALID_RESPONSE", "Invalid References property items."));
2886
+ items.push(...raw.results.map((item) => property(item).rich_text));
2887
+ if (!raw.has_more)
2888
+ break;
2889
+ if (typeof raw.next_cursor !== "string" || seen.has(raw.next_cursor))
2890
+ return yield* Effect7.fail(fail("INVALID_RESPONSE", "References pagination returned a missing or repeating cursor."));
2891
+ cursor = raw.next_cursor;
2892
+ seen.add(cursor);
2893
+ } while (cursor);
2894
+ return items;
2895
+ });
2896
+ }
2897
+ function readReferences(skill, rawPage) {
2898
+ return Effect7.gen(function* () {
2899
+ const api = yield* Notion;
2900
+ const reference = yield* Effect7.try({
2901
+ try: () => referencesProperty(rawPage),
2902
+ catch: (error) => error
2903
+ });
2904
+ if (!reference)
2905
+ return yield* Effect7.fail(fail("INVALID_REFERENCES", "The skill has no References property."));
2906
+ const root = yield* api.request(`v1/pages/${skill.id}/markdown`);
2907
+ const markdown = yield* Effect7.try({
2908
+ try: () => pageMarkdown(root),
2909
+ catch: (error) => error
2910
+ });
2911
+ const entries = yield* propertyEntries(rawPage, reference);
2912
+ const pages = [{ id: skill.id, path: "SKILL.md", markdown }];
2913
+ const paths = new Set(["SKILL.md"]);
2914
+ const ids = new Set([skill.id]);
2915
+ for (const raw of entries) {
2916
+ const entry = property(raw);
2917
+ const mention = property(entry.mention);
2918
+ const linked = property(property(entry.text).link).url ?? entry.href;
2919
+ const id = mention.type === "page" ? pageId(String(property(mention.page).id)) : typeof linked === "string" ? pageId(linked) : undefined;
2920
+ if (!id) {
2921
+ if (text([entry]).trim())
2922
+ return yield* Effect7.fail(fail("INVALID_REFERENCES", "References accepts only Notion page mentions or links.", {
2923
+ page_id: skill.id
2924
+ }));
2925
+ continue;
2926
+ }
2927
+ if (ids.has(id))
2928
+ continue;
2929
+ const rawReference = yield* api.request(`v1/pages/${id}`);
2930
+ if (property(rawReference).in_trash)
2931
+ return yield* Effect7.fail(fail("REFERENCE_NOT_FOUND", "A reference page is in trash.", { page_id: id }));
2932
+ const label = text([entry]);
2933
+ const title = text(Object.values(property(property(rawReference).properties)).map(property).find((value) => value.type === "title")?.title);
2934
+ const path = yield* Effect7.try({
2935
+ try: () => referencePath(/\.md$/i.test(label.trim()) ? label : title),
2936
+ catch: (error) => error
2937
+ });
2938
+ if (paths.has(path))
2939
+ return yield* Effect7.fail(fail("REFERENCE_PATH_CONFLICT", "Reference pages resolve to the same path; label their links with distinct filenames.", { path }));
2940
+ const rawMarkdown = yield* api.request(`v1/pages/${id}/markdown`);
2941
+ const body = yield* Effect7.try({
2942
+ try: () => pageMarkdown(rawMarkdown),
2943
+ catch: (error) => error
2944
+ });
2945
+ ids.add(id);
2946
+ paths.add(path);
2947
+ pages.push({ id, path, markdown: body });
2948
+ }
2949
+ const files = pages.map((page) => page.path === "SKILL.md" ? canonicalMain(skill.name, skill.description, rewritePageLinks(withoutChildPages(page.markdown), page.path, pages, "local")) : {
2950
+ path: page.path,
2951
+ bytes: new TextEncoder().encode(rewritePageLinks(page.markdown, page.path, pages, "local"))
2952
+ });
2953
+ const attachments = Object.values(property(property(rawPage).properties)).map(property).find((value) => value.type === "files");
2954
+ const preserved = [];
2955
+ const attachmentVersions = [];
2956
+ for (const raw of Array.isArray(attachments?.files) ? attachments.files : []) {
2957
+ const attachment = property(raw);
2958
+ const url = property(attachment[typeof attachment.type === "string" ? attachment.type : ""]).url;
2959
+ if (typeof url !== "string" || typeof attachment.name !== "string")
2960
+ return yield* Effect7.fail(fail("INVALID_RESPONSE", "Invalid skill attachment."));
2961
+ const client = HttpClient.withScope(yield* HttpClient.HttpClient);
2962
+ const bytes = yield* Effect7.gen(function* () {
2963
+ for (let attempt = 0;; attempt++) {
2964
+ const downloaded = yield* Effect7.scoped(Effect7.gen(function* () {
2965
+ const response = yield* client.get(url);
2966
+ if (response.status < 200 || response.status >= 300)
2967
+ return yield* Effect7.fail(fail("DOWNLOAD_FAILED", "Could not download a skill attachment.", {
2968
+ path: attachment.name,
2969
+ status: response.status
2970
+ }));
2971
+ return new Uint8Array(yield* response.arrayBuffer);
2972
+ })).pipe(Effect7.timeout("60 seconds"), Effect7.mapError((error) => {
2973
+ if (error instanceof SkillsError)
2974
+ return error;
2975
+ const reason = property(error).reason;
2976
+ const cause = property(reason).cause;
2977
+ const tls = /certificate|TLS|SSL|CERT_/i.test(String(property(cause).code ?? "") + String(property(cause).message ?? ""));
2978
+ return fail("DOWNLOAD_FAILED", "Could not download a skill attachment.", {
2979
+ path: attachment.name,
2980
+ reason: tls ? "tls" : property(error)._tag === "TimeoutError" ? "timeout" : ["TransportError", "DecodeError"].includes(String(property(reason)._tag)) ? "network" : "invalid_response"
2981
+ });
2982
+ }), Effect7.result);
2983
+ if (downloaded._tag === "Success")
2984
+ return downloaded.success;
2985
+ const details = property(downloaded.failure.details);
2986
+ if (attempt < 3 && ([429, 500, 502, 503, 504].includes(Number(details.status)) || ["network", "timeout"].includes(String(details.reason)))) {
2987
+ yield* Effect7.sleep(`${2 ** attempt} seconds`);
2988
+ continue;
2989
+ }
2990
+ return yield* Effect7.fail(downloaded.failure);
2991
+ }
2992
+ });
2993
+ if (bytes.length > 32 * 1024 * 1024)
2994
+ return yield* Effect7.fail(fail("ARCHIVE_TOO_LARGE", "Skill attachment exceeds 32 MiB."));
2995
+ attachmentVersions.push([attachment.name, yield* sha256(bytes)]);
2996
+ if (attachment.name === BUNDLE) {
2997
+ const bundle = yield* Effect7.try({
2998
+ try: () => readPortable(readImportZip(bytes)),
2999
+ catch: (error) => error
3000
+ });
3001
+ if (!bundle)
3002
+ return yield* Effect7.fail(fail("INVALID_ARCHIVE", "Source bundle has no portability manifest."));
3003
+ preserved.push({ path: BUNDLE, bytes }, ...bundle.files.filter((file) => file.path !== bundle.main && !paths.has(file.path) && bundle.projection?.references?.[file.path] === undefined));
3004
+ } else if (!paths.has(attachment.name))
3005
+ preserved.push({ path: normalizePath(attachment.name), bytes });
3006
+ }
3007
+ if (files.length + preserved.length > 1e4 || [...files, ...preserved].reduce((size, file) => size + file.bytes.length, 0) > 128 * 1024 * 1024)
3008
+ return yield* Effect7.fail(fail("ARCHIVE_TOO_LARGE", "Skill content exceeds 128 MiB or 10,000 files."));
3009
+ const version = yield* sha256(JSON.stringify([
3010
+ "references-v1",
3011
+ skill.name,
3012
+ skill.description,
3013
+ entries,
3014
+ pages,
3015
+ attachmentVersions
3016
+ ]));
3017
+ return {
3018
+ property_id: String(reference.id),
3019
+ pages,
3020
+ files: [...files, ...preserved],
3021
+ version_id: version
3022
+ };
3023
+ }).pipe(Effect7.mapError((error) => error instanceof SkillsError ? error : fail("DOWNLOAD_FAILED", "Could not download a skill attachment.")));
3024
+ }
3025
+
2130
3026
  // packages/core/src/snapshot.ts
2131
3027
  function loadSnapshot(id) {
2132
- return Effect5.gen(function* () {
3028
+ return Effect8.gen(function* () {
2133
3029
  if (!/^s_[a-f0-9]{64}$/.test(id))
2134
- return yield* Effect5.fail(fail("INVALID_SNAPSHOT", "Invalid snapshot ID."));
3030
+ return yield* Effect8.fail(fail("INVALID_SNAPSHOT", "Invalid snapshot ID."));
2135
3031
  const store = yield* Store;
2136
3032
  const snapshot = yield* store.readJson(`snapshots/${id}.json`, SnapshotSchema);
2137
3033
  if (!snapshot)
2138
- return yield* Effect5.fail(fail("SNAPSHOT_MISSING", "This snapshot has not been cached on this machine.", {
3034
+ return yield* Effect8.fail(fail("SNAPSHOT_MISSING", "This snapshot has not been cached on this machine.", {
2139
3035
  snapshot_id: id
2140
3036
  }));
2141
3037
  if (snapshot.snapshot_id !== id || snapshot.files.some((f) => !/^[a-f0-9]{64}$/.test(f.sha256)))
2142
- return yield* Effect5.fail(fail("STATE_CORRUPT", "The snapshot manifest is invalid."));
2143
- return snapshot;
3038
+ return yield* Effect8.fail(fail("STATE_CORRUPT", "The snapshot manifest is invalid."));
3039
+ return yield* validateSnapshot(snapshot);
2144
3040
  });
2145
3041
  }
2146
3042
  function openSkill(selector, options = {}) {
2147
- return Effect5.gen(function* () {
3043
+ return Effect8.gen(function* () {
3044
+ const startedAt = yield* Clock3.currentTimeMillis;
2148
3045
  const api = yield* Notion;
2149
3046
  const store = yield* Store;
2150
3047
  const id = pageId(selector);
@@ -2154,7 +3051,7 @@ function openSkill(selector, options = {}) {
2154
3051
  const selectedDatabase = options.database === undefined ? undefined : yield* databaseId(options.database);
2155
3052
  scope = yield* authScope;
2156
3053
  const raw = yield* api.request(`v1/pages/${id}`);
2157
- const row = yield* Effect5.try({
3054
+ const row = yield* Effect8.try({
2158
3055
  try: () => decode(PageSchema, raw),
2159
3056
  catch: () => fail("INVALID_RESPONSE", "Invalid skill page response.")
2160
3057
  });
@@ -2162,31 +3059,69 @@ function openSkill(selector, options = {}) {
2162
3059
  const databaseId2 = parent.database_id;
2163
3060
  const dataSourceId = parent.data_source_id;
2164
3061
  if (typeof databaseId2 !== "string" || typeof dataSourceId !== "string" || row.in_trash)
2165
- return yield* Effect5.fail(fail("NOT_SKILL", "The page must belong to an accessible Skills Database."));
3062
+ return yield* Effect8.fail(fail("NOT_SKILL", "The page must belong to an accessible skill database."));
2166
3063
  if (selectedDatabase !== undefined && selectedDatabase !== databaseId2)
2167
- return yield* Effect5.fail(fail("SKILL_NOT_FOUND", "The skill does not belong to the selected database."));
3064
+ return yield* Effect8.fail(fail("SKILL_NOT_FOUND", "The skill does not belong to the selected database."));
2168
3065
  const source = yield* explicitSource(databaseId2);
2169
- skill = yield* Effect5.try({
3066
+ skill = yield* Effect8.try({
2170
3067
  try: () => skillFromPage(row, source, dataSourceId),
2171
3068
  catch: (e) => e
2172
3069
  });
2173
3070
  } else {
2174
- const directory = yield* catalog(options);
3071
+ const directory = yield* catalog({ database: options.database, refresh: true });
2175
3072
  scope = directory.scope;
2176
- skill = yield* Effect5.try({
3073
+ skill = yield* Effect8.try({
2177
3074
  try: () => resolveSkill(selector, directory),
2178
3075
  catch: (e) => e
2179
3076
  });
2180
3077
  }
3078
+ const generation = yield* store.reserveCacheGeneration(scope, skill.id);
3079
+ const rawPage = yield* api.request(`v1/pages/${skill.id}`);
3080
+ const hasReferences = yield* Effect8.try({
3081
+ try: () => referencesProperty(rawPage),
3082
+ catch: (error) => error
3083
+ });
3084
+ if (hasReferences) {
3085
+ const graph = yield* readReferences(skill, rawPage);
3086
+ const snapshotId = `s_${yield* sha256(JSON.stringify([scope, skill.id, graph.version_id]))}`;
3087
+ const cachedResult = yield* loadSnapshot(snapshotId).pipe(Effect8.result);
3088
+ if (cachedResult._tag === "Success")
3089
+ return yield* publishSnapshotObservation(cachedResult.success, startedAt, generation);
3090
+ const files = [];
3091
+ const paths = new Set;
3092
+ for (const file of graph.files.sort((a, b) => a.path.localeCompare(b.path))) {
3093
+ if (paths.has(file.path))
3094
+ return yield* Effect8.fail(fail("REFERENCE_PATH_CONFLICT", "A reference and attachment share a path.", {
3095
+ path: file.path
3096
+ }));
3097
+ paths.add(file.path);
3098
+ const hash = yield* sha256(file.bytes);
3099
+ yield* store.writeBytes(`objects/${hash}`, file.bytes);
3100
+ files.push({ path: file.path, bytes: file.bytes.length, sha256: hash });
3101
+ }
3102
+ const snapshot = {
3103
+ snapshot_id: snapshotId,
3104
+ scope,
3105
+ skill,
3106
+ skill_name: skill.alias,
3107
+ version_id: graph.version_id,
3108
+ created_at: yield* Clock3.currentTimeMillis,
3109
+ files,
3110
+ references: graph.pages
3111
+ };
3112
+ yield* store.writeJson(`snapshots/${snapshotId}.json`, snapshot);
3113
+ return yield* publishSnapshotObservation(snapshot, startedAt, generation);
3114
+ }
2181
3115
  const raw = yield* api.request(`v1/ai/skills/${skill.id}`);
2182
- const exported = yield* Effect5.try({
3116
+ const exported = yield* Effect8.try({
2183
3117
  try: () => decode(ExportSchema, raw),
2184
3118
  catch: () => fail("INVALID_RESPONSE", "Invalid skill export response.")
2185
3119
  });
2186
3120
  if (exported.id !== skill.id)
2187
- return yield* Effect5.fail(fail("INVALID_RESPONSE", "The exported skill ID differs from the requested page."));
3121
+ return yield* Effect8.fail(fail("INVALID_RESPONSE", "The exported skill ID differs from the requested page."));
2188
3122
  const snapshotId = `s_${yield* sha256(JSON.stringify([scope, skill.id, exported.version_id]))}`;
2189
- const cached = yield* store.readJson(`snapshots/${snapshotId}.json`, SnapshotSchema);
3123
+ const cachedResult = yield* loadSnapshot(snapshotId).pipe(Effect8.result);
3124
+ const cached = cachedResult._tag === "Success" ? cachedResult.success : undefined;
2190
3125
  const validateName = (name) => {
2191
3126
  if (name !== skill.alias)
2192
3127
  throw fail("INVALID_SKILL", "SKILL.md name must equal the lowercase, hyphenated Notion Name.", {
@@ -2196,25 +3131,25 @@ function openSkill(selector, options = {}) {
2196
3131
  });
2197
3132
  };
2198
3133
  if (cached) {
2199
- yield* Effect5.try({
3134
+ yield* Effect8.try({
2200
3135
  try: () => validateName(cached.skill_name),
2201
3136
  catch: (e) => e
2202
3137
  });
2203
- return cached;
3138
+ return yield* publishSnapshotObservation(cached, startedAt, generation);
2204
3139
  }
2205
- const downloaded = yield* Effect5.gen(function* () {
2206
- const client = yield* HttpClient.HttpClient;
3140
+ const downloaded = yield* Effect8.gen(function* () {
3141
+ const client = yield* HttpClient2.HttpClient;
2207
3142
  const response = yield* client.get(exported.url);
2208
3143
  if (response.status < 200 || response.status >= 300)
2209
- return yield* Effect5.fail(fail("DOWNLOAD_FAILED", "The skill archive could not be downloaded.", {
3144
+ return yield* Effect8.fail(fail("DOWNLOAD_FAILED", "The skill archive could not be downloaded.", {
2210
3145
  status: response.status
2211
3146
  }));
2212
3147
  const chunks = [];
2213
3148
  const length = yield* response.stream.pipe(Stream2.runFoldEffect(() => 0, (size, chunk) => {
2214
3149
  if (size + chunk.length > 32 * 1024 * 1024)
2215
- return Effect5.fail(fail("ARCHIVE_TOO_LARGE", "Compressed skill archive exceeds 32 MiB."));
3150
+ return Effect8.fail(fail("ARCHIVE_TOO_LARGE", "Compressed skill archive exceeds 32 MiB."));
2216
3151
  chunks.push(chunk);
2217
- return Effect5.succeed(size + chunk.length);
3152
+ return Effect8.succeed(size + chunk.length);
2218
3153
  }));
2219
3154
  const bytes = new Uint8Array(length);
2220
3155
  let at = 0;
@@ -2223,14 +3158,14 @@ function openSkill(selector, options = {}) {
2223
3158
  at += chunk.length;
2224
3159
  }
2225
3160
  return bytes;
2226
- }).pipe(Effect5.timeout("60 seconds"), Effect5.mapError((e) => e instanceof SkillsError ? e : fail("DOWNLOAD_FAILED", "The skill archive download failed or timed out. Read the current target again to obtain a fresh URL.")));
2227
- const archive = yield* Effect5.try({
3161
+ }).pipe(Effect8.timeout("60 seconds"), Effect8.mapError((e) => e instanceof SkillsError ? e : fail("DOWNLOAD_FAILED", "The skill archive download failed or timed out. Read the current target again to obtain a fresh URL.")));
3162
+ const archive = yield* Effect8.try({
2228
3163
  try: () => readArchive(downloaded),
2229
3164
  catch: (e) => e
2230
3165
  });
2231
- yield* Effect5.try({ try: () => validateName(archive.name), catch: (e) => e });
3166
+ yield* Effect8.try({ try: () => validateName(archive.name), catch: (e) => e });
2232
3167
  const sourceBundle = archive.files.find((file) => file.path === BUNDLE);
2233
- const preserved = sourceBundle ? yield* Effect5.try({
3168
+ const preserved = sourceBundle ? yield* Effect8.try({
2234
3169
  try: () => readPortable(readImportZip(sourceBundle.data)),
2235
3170
  catch: (e) => e
2236
3171
  }) : undefined;
@@ -2251,11 +3186,11 @@ function openSkill(selector, options = {}) {
2251
3186
  skill,
2252
3187
  skill_name: archive.name,
2253
3188
  version_id: exported.version_id,
2254
- created_at: yield* Clock2.currentTimeMillis,
3189
+ created_at: yield* Clock3.currentTimeMillis,
2255
3190
  files
2256
3191
  };
2257
3192
  yield* store.writeJson(`snapshots/${snapshotId}.json`, snapshot);
2258
- return snapshot;
3193
+ return yield* publishSnapshotObservation(snapshot, startedAt, generation);
2259
3194
  });
2260
3195
  }
2261
3196
  function snapshotInfo(snapshot) {
@@ -2270,26 +3205,80 @@ function snapshotInfo(snapshot) {
2270
3205
  path: f.path,
2271
3206
  bytes: f.bytes,
2272
3207
  ref: fileRef(snapshot.skill.id, f.path, snapshot.snapshot_id)
2273
- }))
3208
+ })),
3209
+ ...snapshot.source ? { source: snapshot.source } : {},
3210
+ ...snapshot.freshness ? { freshness: snapshot.freshness } : {}
2274
3211
  };
2275
3212
  }
2276
3213
  function targetSnapshot(target, options = {}) {
2277
- return Effect5.gen(function* () {
2278
- const snapshot = target.snapshot ? yield* loadSnapshot(target.snapshot) : yield* openSkill(target.selector, options);
3214
+ return Effect8.gen(function* () {
3215
+ yield* Effect8.try({
3216
+ try: () => validateReadPolicy(options, Boolean(target.snapshot)),
3217
+ catch: (error) => error
3218
+ });
3219
+ let snapshot;
3220
+ if (target.snapshot)
3221
+ snapshot = {
3222
+ ...yield* loadSnapshot(target.snapshot),
3223
+ source: "local_snapshot",
3224
+ freshness: { policy: "pinned" }
3225
+ };
3226
+ else {
3227
+ const maxAge = options.maxAge ?? (yield* effectiveCachePolicy).read_max_age_ms;
3228
+ const scopeResult = yield* locallySelectedScope(Boolean(options.offline)).pipe(Effect8.result);
3229
+ if (scopeResult._tag === "Failure" && options.offline)
3230
+ return yield* Effect8.fail(scopeResult.failure);
3231
+ const scope = scopeResult._tag === "Success" ? scopeResult.success : undefined;
3232
+ let selected = pageId(target.selector);
3233
+ if (!selected && !options.refresh) {
3234
+ const directoryResult = yield* catalog(options).pipe(Effect8.result);
3235
+ if (directoryResult._tag === "Failure")
3236
+ return yield* Effect8.fail(directoryResult.failure);
3237
+ selected = yield* Effect8.try({
3238
+ try: () => resolveSkill(target.selector, directoryResult.success).id,
3239
+ catch: (error) => error
3240
+ });
3241
+ }
3242
+ const observedResult = scope && selected && !options.refresh ? yield* cachedRemoteObservation(selected, scope).pipe(Effect8.result) : undefined;
3243
+ if (observedResult?._tag === "Failure" && options.offline)
3244
+ return yield* Effect8.fail(observedResult.failure);
3245
+ const observed = observedResult?._tag === "Success" ? observedResult.success : undefined;
3246
+ const now = yield* Clock3.currentTimeMillis;
3247
+ const age = observed ? now - observed.validated_at : NaN;
3248
+ if (observed && (options.offline || Number.isFinite(age) && age >= 0 && age < maxAge)) {
3249
+ if (options.database !== undefined && observed.snapshot.skill.database_id !== (yield* databaseId(options.database)))
3250
+ return yield* Effect8.fail(fail("SKILL_NOT_FOUND", "The Skill does not belong to the selected database."));
3251
+ snapshot = {
3252
+ ...observed.snapshot,
3253
+ source: "local_cache",
3254
+ freshness: freshness(options, observed.validated_at, now, maxAge)
3255
+ };
3256
+ } else {
3257
+ if (options.offline)
3258
+ return yield* Effect8.fail(fail("CACHE_MISSING", "No complete Skill observation is available in the selected scope."));
3259
+ const online = yield* openSkill(options.refresh ? target.selector : selected ?? target.selector, { database: options.database });
3260
+ const validatedAt = online.freshness?.validated_at ? Date.parse(online.freshness.validated_at) : yield* Clock3.currentTimeMillis;
3261
+ snapshot = {
3262
+ ...online,
3263
+ source: "notion",
3264
+ freshness: freshness(options, validatedAt, yield* Clock3.currentTimeMillis, maxAge)
3265
+ };
3266
+ }
3267
+ }
2279
3268
  if (target.snapshot && target.selector && ![snapshot.skill.id, snapshot.skill.name, snapshot.skill.alias].includes(pageId(target.selector) ?? target.selector))
2280
- return yield* Effect5.fail(fail("SNAPSHOT_CONFLICT", "The snapshot belongs to another Skill."));
3269
+ return yield* Effect8.fail(fail("SNAPSHOT_CONFLICT", "The snapshot belongs to another Skill."));
2281
3270
  if (target.snapshot && options.database !== undefined && snapshot.skill.database_id !== (yield* databaseId(options.database)))
2282
- return yield* Effect5.fail(fail("SKILL_NOT_FOUND", "The Skill does not belong to the selected database."));
3271
+ return yield* Effect8.fail(fail("SKILL_NOT_FOUND", "The Skill does not belong to the selected database."));
2283
3272
  return snapshot;
2284
3273
  });
2285
3274
  }
2286
3275
  function readSkill(input, options = {}) {
2287
- return Effect5.gen(function* () {
3276
+ return Effect8.gen(function* () {
2288
3277
  if (options.from && options.path !== undefined)
2289
- return yield* Effect5.fail(fail("INVALID_ARGUMENT", "--from and --path cannot be combined."));
3278
+ return yield* Effect8.fail(fail("INVALID_ARGUMENT", "--from and --path cannot be combined."));
2290
3279
  if (options.output && options.lines)
2291
- return yield* Effect5.fail(fail("INVALID_ARGUMENT", "--output and --lines cannot be combined."));
2292
- const target = yield* Effect5.try({
3280
+ return yield* Effect8.fail(fail("INVALID_ARGUMENT", "--output and --lines cannot be combined."));
3281
+ const target = yield* Effect8.try({
2293
3282
  try: () => {
2294
3283
  if (options.from && (/^[a-z]+:/i.test(input) || input.startsWith("s_")))
2295
3284
  throw fail("INVALID_ARGUMENT", "--from requires a relative file path.");
@@ -2301,21 +3290,22 @@ function readSkill(input, options = {}) {
2301
3290
  const snapshot = yield* targetSnapshot(target, options);
2302
3291
  const file = snapshot.files.find((f) => f.path === path);
2303
3292
  if (!file)
2304
- return yield* Effect5.fail(fail("FILE_NOT_FOUND", "The file does not exist in this snapshot.", {
3293
+ return yield* Effect8.fail(fail("FILE_NOT_FOUND", "The file does not exist in this snapshot.", {
2305
3294
  path,
2306
3295
  available: snapshot.files.map((f) => f.path)
2307
3296
  }));
2308
3297
  const store = yield* Store;
2309
3298
  const bytes = yield* store.readBytes(`objects/${file.sha256}`);
2310
3299
  if (bytes.length !== file.bytes || (yield* sha256(bytes)) !== file.sha256)
2311
- return yield* Effect5.fail(fail("STATE_CORRUPT", "The cached file failed its content checksum."));
3300
+ return yield* Effect8.fail(fail("STATE_CORRUPT", "The cached file failed its content checksum."));
2312
3301
  const metadata = {
2313
3302
  skill: snapshot.skill,
2314
3303
  snapshot_id: snapshot.snapshot_id,
2315
3304
  version_id: snapshot.version_id,
2316
3305
  path,
2317
3306
  ref: fileRef(snapshot.skill.id, path, snapshot.snapshot_id),
2318
- source: target.snapshot ? "local_snapshot" : "notion"
3307
+ source: snapshot.source,
3308
+ freshness: snapshot.freshness
2319
3309
  };
2320
3310
  if (options.output) {
2321
3311
  return {
@@ -2324,7 +3314,7 @@ function readSkill(input, options = {}) {
2324
3314
  bytes: bytes.length
2325
3315
  };
2326
3316
  }
2327
- const content = yield* Effect5.try({
3317
+ const content = yield* Effect8.try({
2328
3318
  try: () => {
2329
3319
  if (bytes.includes(0))
2330
3320
  throw new Error("binary");
@@ -2339,11 +3329,11 @@ function readSkill(input, options = {}) {
2339
3329
  if (options.lines) {
2340
3330
  const range = /^(\d+)(?:-(\d+))?$/.exec(options.lines);
2341
3331
  if (!range)
2342
- return yield* Effect5.fail(fail("INVALID_RANGE", "Expected --lines <start>-<end>, using inclusive 1-based line numbers."));
3332
+ return yield* Effect8.fail(fail("INVALID_RANGE", "Expected --lines <start>-<end>, using inclusive 1-based line numbers."));
2343
3333
  start = Number(range[1]);
2344
3334
  end = Number(range[2] ?? range[1]);
2345
3335
  if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 1 || end < start || start > lines.length)
2346
- return yield* Effect5.fail(fail("INVALID_RANGE", "Line range is outside the file.", { total_lines: lines.length }));
3336
+ return yield* Effect8.fail(fail("INVALID_RANGE", "Line range is outside the file.", { total_lines: lines.length }));
2347
3337
  end = Math.min(end, lines.length);
2348
3338
  }
2349
3339
  return {
@@ -2356,8 +3346,8 @@ function readSkill(input, options = {}) {
2356
3346
  });
2357
3347
  }
2358
3348
  function listSkill(input, options = {}) {
2359
- return Effect5.gen(function* () {
2360
- const target = yield* Effect5.try({
3349
+ return Effect8.gen(function* () {
3350
+ const target = yield* Effect8.try({
2361
3351
  try: () => parseTarget(input, options.path),
2362
3352
  catch: (e) => e
2363
3353
  });
@@ -2365,7 +3355,7 @@ function listSkill(input, options = {}) {
2365
3355
  const path = target.path ?? "";
2366
3356
  const files = snapshot.files.filter((f) => !path || f.path.startsWith(path + "/") || f.path === path);
2367
3357
  if (path && !files.length)
2368
- return yield* Effect5.fail(fail("FILE_NOT_FOUND", "No file or directory matches this path.", { path }));
3358
+ return yield* Effect8.fail(fail("FILE_NOT_FOUND", "No file or directory matches this path.", { path }));
2369
3359
  return {
2370
3360
  ...snapshotInfo(snapshot),
2371
3361
  files: files.map((f) => ({
@@ -2377,22 +3367,22 @@ function listSkill(input, options = {}) {
2377
3367
  });
2378
3368
  }
2379
3369
  // packages/core/src/mutation.ts
2380
- import { Effect as Effect7, FileSystem as FileSystem4, Path as Path4 } from "effect";
3370
+ import { Effect as Effect11, FileSystem as FileSystem4, Path as Path4 } from "effect";
2381
3371
  import { parse as parse4 } from "effect/encoding/Yaml";
2382
3372
 
2383
3373
  // packages/core/src/export.ts
2384
- import { Effect as Effect6, FileSystem as FileSystem3, Path as Path3 } from "effect";
3374
+ import { Effect as Effect9, FileSystem as FileSystem3, Path as Path3 } from "effect";
2385
3375
  function snapshotPortable(snapshot) {
2386
- return Effect6.gen(function* () {
3376
+ return Effect9.gen(function* () {
2387
3377
  const store = yield* Store;
2388
3378
  const files = [];
2389
3379
  for (const file of snapshot.files) {
2390
3380
  const bytes = yield* store.readBytes(`objects/${file.sha256}`);
2391
3381
  if (bytes.length !== file.bytes || (yield* sha256(bytes)) !== file.sha256)
2392
- return yield* Effect6.fail(fail("STATE_CORRUPT", "Export file failed its checksum.", { path: file.path }));
3382
+ return yield* Effect9.fail(fail("STATE_CORRUPT", "Export file failed its checksum.", { path: file.path }));
2393
3383
  files.push({ path: file.path, bytes });
2394
3384
  }
2395
- return yield* Effect6.try({
3385
+ return yield* Effect9.try({
2396
3386
  try: () => {
2397
3387
  const main = files.find((file) => file.path === "SKILL.md");
2398
3388
  if (!main)
@@ -2419,11 +3409,23 @@ function snapshotPortable(snapshot) {
2419
3409
  const unchanged = projection && projection.name === snapshot.skill.name && projection.description === doc.description && projection.body === bodyIdentity(doc.body);
2420
3410
  const original = source.files.find((file) => file.path === source.main);
2421
3411
  const merged = new Map(source.files.map((file) => [file.path, file]));
3412
+ if (snapshot.references && projection?.references) {
3413
+ const live = new Set(snapshot.references.map((page) => page.path));
3414
+ for (const path of Object.keys(projection.references))
3415
+ if (!live.has(path))
3416
+ merged.delete(path);
3417
+ }
2422
3418
  if (!unchanged)
2423
3419
  merged.set(source.main, canonicalMain(snapshot.skill.name, doc.description, doc.body, original));
2424
3420
  for (const file of files)
2425
3421
  if (file.path !== "SKILL.md" && file.path !== BUNDLE && file.path !== MANIFEST && file.path !== source.main)
2426
- merged.set(file.path, file);
3422
+ if (snapshot.references && projection?.references?.[file.path] !== undefined) {
3423
+ const currentBody = new TextDecoder("utf-8", { fatal: true }).decode(file.bytes);
3424
+ if (bodyIdentity(currentBody) === projection.references[file.path])
3425
+ continue;
3426
+ merged.set(file.path, file);
3427
+ } else
3428
+ merged.set(file.path, file);
2427
3429
  return {
2428
3430
  name: snapshot.skill.name,
2429
3431
  description: doc.description,
@@ -2436,7 +3438,7 @@ function snapshotPortable(snapshot) {
2436
3438
  });
2437
3439
  }
2438
3440
  function portableIdentity(skill) {
2439
- return Effect6.gen(function* () {
3441
+ return Effect9.gen(function* () {
2440
3442
  const files = [];
2441
3443
  for (const file of [...skill.files].sort(fileOrder))
2442
3444
  files.push([file.path, yield* sha256(file.bytes)]);
@@ -2444,15 +3446,15 @@ function portableIdentity(skill) {
2444
3446
  });
2445
3447
  }
2446
3448
  function exportSkill(selectorInput, options) {
2447
- return Effect6.gen(function* () {
2448
- const target = yield* Effect6.try({
3449
+ return Effect9.gen(function* () {
3450
+ const target = yield* Effect9.try({
2449
3451
  try: () => parseTarget(selectorInput),
2450
3452
  catch: (e) => e
2451
3453
  });
2452
3454
  const snapshot = yield* targetSnapshot(target, options);
2453
3455
  const skill = yield* snapshotPortable(snapshot);
2454
3456
  const format = options.format ?? (/\.zip$/i.test(options.output) ? "zip" : "directory");
2455
- const files = yield* Effect6.try({
3457
+ const files = yield* Effect9.try({
2456
3458
  try: () => portableFiles(skill),
2457
3459
  catch: (e) => e
2458
3460
  });
@@ -2461,7 +3463,7 @@ function exportSkill(selectorInput, options) {
2461
3463
  const destination = path.resolve(options.output);
2462
3464
  let reused = false;
2463
3465
  if (format === "zip") {
2464
- const bytes = yield* Effect6.try({
3466
+ const bytes = yield* Effect9.try({
2465
3467
  try: () => portableZip(skill),
2466
3468
  catch: (e) => e
2467
3469
  });
@@ -2470,17 +3472,17 @@ function exportSkill(selectorInput, options) {
2470
3472
  } else {
2471
3473
  const exists = yield* fs.exists(destination);
2472
3474
  if (exists) {
2473
- const names = yield* fs.readDirectory(destination, { recursive: true }).pipe(Effect6.mapError(() => fail("OUTPUT_CONFLICT", "Output is not an identical Skill directory.")));
3475
+ const names = yield* fs.readDirectory(destination, { recursive: true }).pipe(Effect9.mapError(() => fail("OUTPUT_CONFLICT", "Output is not an identical Skill directory.")));
2474
3476
  const existing = [];
2475
3477
  for (const name of names)
2476
3478
  if ((yield* fs.stat(path.join(destination, name))).type !== "Directory")
2477
3479
  existing.push(name.split(path.sep).join("/"));
2478
3480
  if (JSON.stringify(existing.sort()) !== JSON.stringify(files.map((file) => file.path).sort()))
2479
- return yield* Effect6.fail(fail("OUTPUT_CONFLICT", "Output directory contains different files."));
3481
+ return yield* Effect9.fail(fail("OUTPUT_CONFLICT", "Output directory contains different files."));
2480
3482
  for (const file of files) {
2481
3483
  const old = yield* fs.readFile(path.join(destination, normalizePath(file.path)));
2482
3484
  if ((yield* sha256(old)) !== (yield* sha256(file.bytes)))
2483
- return yield* Effect6.fail(fail("OUTPUT_CONFLICT", "Existing output file differs.", { path: file.path }));
3485
+ return yield* Effect9.fail(fail("OUTPUT_CONFLICT", "Existing output file differs.", { path: file.path }));
2484
3486
  }
2485
3487
  reused = true;
2486
3488
  } else {
@@ -2502,14 +3504,270 @@ function exportSkill(selectorInput, options) {
2502
3504
  main_path: skill.main,
2503
3505
  files: files.map((file) => ({ path: file.path, bytes: file.bytes.length }))
2504
3506
  };
2505
- }).pipe(Effect6.mapError((error) => error instanceof SkillsError ? error : fail("OUTPUT_FAILED", "Could not write the Skill export; inspect output before retrying.", { output: options.output })));
3507
+ }).pipe(Effect9.mapError((error) => error instanceof SkillsError ? error : fail("OUTPUT_FAILED", "Could not write the Skill export; inspect output before retrying.", { output: options.output })));
2506
3508
  }
2507
3509
 
2508
- // packages/core/src/mutation.ts
2509
- var DESCRIPTION = "notion%3A%2F%2Fskills%2Fdescription_property";
2510
- var FILES = "notion%3A%2F%2Fskills%2Ffiles_property";
2511
- var decoder4 = new TextDecoder("utf-8", { fatal: true });
2512
- function skillDocument(bytes) {
3510
+ // packages/core/src/reference-mutation.ts
3511
+ import { Effect as Effect10 } from "effect";
3512
+ function referenceContentIdentity(portable) {
3513
+ return Effect10.gen(function* () {
3514
+ const files = yield* Effect10.try({
3515
+ try: () => {
3516
+ const main = portable.files.find((file) => file.path === portable.main);
3517
+ const doc = importDocument(main, { name: portable.name, description: portable.description });
3518
+ const pages = portable.files.map((file, index) => ({
3519
+ id: `00000000-0000-4000-8000-${String(index).padStart(12, "0")}`,
3520
+ path: file.path === portable.main ? "SKILL.md" : file.path,
3521
+ markdown: ""
3522
+ }));
3523
+ const normalized = (body, path) => bodyIdentity(rewritePageLinks(rewritePageLinks(body, path, pages, "notion"), path, pages, "local"));
3524
+ return portable.files.map((file) => file.path === portable.main ? canonicalMain(portable.name, portable.description, normalized(doc.body, "SKILL.md")) : {
3525
+ ...file,
3526
+ bytes: new TextEncoder().encode(normalized(new TextDecoder("utf-8", { fatal: true }).decode(file.bytes), file.path))
3527
+ });
3528
+ },
3529
+ catch: (error) => error instanceof SkillsError ? error : fail("INVALID_REFERENCES", "Page-only skills require UTF-8 Markdown files.")
3530
+ });
3531
+ return yield* portableIdentity({ ...portable, main: "SKILL.md", files });
3532
+ });
3533
+ }
3534
+ function referenceInput(portable, hasFiles) {
3535
+ return Effect10.gen(function* () {
3536
+ const referenceFiles = portable.files.filter((file) => file.path !== portable.main && /^references\/.*\.md$/i.test(file.path));
3537
+ const otherFiles = portable.files.filter((file) => file.path !== portable.main && !referenceFiles.includes(file));
3538
+ if (!hasFiles && otherFiles.length)
3539
+ return yield* Effect10.fail(fail("UNSUPPORTED_FILE", "This database needs a Files property to retain non-reference files.", { paths: otherFiles.map((file) => file.path) }));
3540
+ if (referenceFiles.length > 100)
3541
+ return yield* Effect10.fail(fail("INVALID_REFERENCES", "References supports at most 100 pages per skill."));
3542
+ const bodies = new Map;
3543
+ for (const file of referenceFiles) {
3544
+ const body = yield* Effect10.try({
3545
+ try: () => new TextDecoder("utf-8", { fatal: true }).decode(file.bytes),
3546
+ catch: () => fail("INVALID_REFERENCES", "Reference Markdown must be UTF-8.", { path: file.path })
3547
+ });
3548
+ if (body.includes("\x00"))
3549
+ return yield* Effect10.fail(fail("INVALID_REFERENCES", "Reference Markdown must be text.", { path: file.path }));
3550
+ bodies.set(file.path, body);
3551
+ }
3552
+ return { referenceFiles, bodies };
3553
+ });
3554
+ }
3555
+ function saveReferences(portable, doc, props, source, operation, current, upload) {
3556
+ return Effect10.gen(function* () {
3557
+ const api = yield* Notion;
3558
+ const contentId = yield* portableIdentity(portable);
3559
+ const { referenceFiles, bodies } = yield* referenceInput(portable, Boolean(props.files));
3560
+ const completed = [];
3561
+ let id = current?.skill.id;
3562
+ let stage = "prepare";
3563
+ const checkVersion = (snapshot) => Effect10.gen(function* () {
3564
+ const latest = yield* openSkill(snapshot.skill.id, { refresh: true });
3565
+ if (latest.version_id !== snapshot.version_id)
3566
+ return yield* Effect10.fail(fail("WRITE_CONFLICT", "The skill or a reference page changed; read it again before writing.", {
3567
+ page_id: snapshot.skill.id,
3568
+ expected_version: snapshot.version_id,
3569
+ actual_version: latest.version_id
3570
+ }));
3571
+ });
3572
+ return yield* Effect10.gen(function* () {
3573
+ if (current)
3574
+ yield* checkVersion(current);
3575
+ else {
3576
+ stage = "create_page";
3577
+ const raw = yield* api.request("v1/pages", {
3578
+ parent: { type: "data_source_id", data_source_id: source.data_source_id },
3579
+ properties: {
3580
+ [props.title]: { title: [{ text: { content: doc.name } }] },
3581
+ [props.description]: { rich_text: [{ text: { content: doc.description } }] }
3582
+ }
3583
+ });
3584
+ completed.push(stage);
3585
+ id = decode(PageSchema, raw).id;
3586
+ }
3587
+ const existing = [...current?.references ?? []];
3588
+ if (current) {
3589
+ let cursor;
3590
+ const seen = new Set;
3591
+ do {
3592
+ const children = property(yield* api.request(`v1/blocks/${id}/children?page_size=100${cursor ? `&start_cursor=${encodeURIComponent(cursor)}` : ""}`));
3593
+ if (!Array.isArray(children.results) || typeof children.has_more !== "boolean")
3594
+ return yield* Effect10.fail(fail("INVALID_RESPONSE", "Invalid child-page response."));
3595
+ for (const raw of children.results) {
3596
+ const child = property(raw);
3597
+ const title = property(child.child_page).title;
3598
+ if (child.type !== "child_page" || typeof title !== "string" || !/\.md$/i.test(title))
3599
+ continue;
3600
+ const path = referencePath(title);
3601
+ if (!referenceFiles.some((file) => file.path === path))
3602
+ continue;
3603
+ const previous = existing.find((page) => page.path === path);
3604
+ if (previous && previous.id !== child.id)
3605
+ return yield* Effect10.fail(fail("REFERENCE_PATH_CONFLICT", "Multiple child pages identify the same reference.", {
3606
+ path,
3607
+ page_ids: [previous.id, child.id]
3608
+ }));
3609
+ if (!previous) {
3610
+ if (typeof child.id !== "string")
3611
+ return yield* Effect10.fail(fail("INVALID_RESPONSE", "Child page has no ID."));
3612
+ existing.push({ id: child.id, path, markdown: "" });
3613
+ }
3614
+ }
3615
+ if (!children.has_more)
3616
+ break;
3617
+ if (typeof children.next_cursor !== "string" || seen.has(children.next_cursor))
3618
+ return yield* Effect10.fail(fail("INVALID_RESPONSE", "Invalid child-page pagination."));
3619
+ cursor = children.next_cursor;
3620
+ seen.add(cursor);
3621
+ } while (cursor);
3622
+ }
3623
+ const pages = [{ id, path: "SKILL.md", markdown: "" }];
3624
+ const register = (references) => api.request(`v1/pages/${id}`, {
3625
+ properties: {
3626
+ [props.references]: {
3627
+ rich_text: references.filter((page) => page.path !== "SKILL.md").flatMap((page, index) => [
3628
+ ...index ? [{ type: "text", text: { content: `
3629
+ ` } }] : [],
3630
+ {
3631
+ type: "text",
3632
+ text: {
3633
+ content: page.path,
3634
+ link: { url: `https://www.notion.so/${page.id.replaceAll("-", "")}` }
3635
+ }
3636
+ }
3637
+ ])
3638
+ }
3639
+ }
3640
+ }, { method: "PATCH" });
3641
+ for (const file of referenceFiles) {
3642
+ const old = existing.find((page) => page.path === file.path);
3643
+ if (old)
3644
+ pages.push(old);
3645
+ else {
3646
+ stage = `create_reference:${file.path}`;
3647
+ const raw = yield* api.request("v1/pages", {
3648
+ parent: { type: "page_id", page_id: id },
3649
+ properties: {
3650
+ title: { title: [{ text: { content: file.path.slice("references/".length) } }] }
3651
+ }
3652
+ });
3653
+ completed.push(stage);
3654
+ pages.push({ id: decode(PageSchema, raw).id, path: file.path, markdown: "" });
3655
+ stage = `register_reference:${file.path}`;
3656
+ yield* register([
3657
+ ...existing.filter((page) => !pages.some((allocated) => allocated.id === page.id)),
3658
+ ...pages
3659
+ ]);
3660
+ completed.push(stage);
3661
+ }
3662
+ }
3663
+ stage = "references";
3664
+ yield* register([
3665
+ ...existing.filter((page) => !pages.some((allocated) => allocated.id === page.id)),
3666
+ ...pages
3667
+ ]);
3668
+ completed.push(stage);
3669
+ let checkpoint = yield* openSkill(id, { refresh: true });
3670
+ const writePage = (page, body) => Effect10.gen(function* () {
3671
+ const before = pageMarkdown(yield* api.request(`v1/pages/${page.id}/markdown`));
3672
+ const content = rewritePageLinks(body, page.path, pages, "notion");
3673
+ const tags = childPageTags(before);
3674
+ const next = tags.length ? `${content.trim()}
3675
+ ${tags.join(`
3676
+ `)}` : content;
3677
+ if (bodyIdentity(before) !== bodyIdentity(next)) {
3678
+ yield* checkVersion(checkpoint);
3679
+ stage = `body:${page.path}`;
3680
+ const written = yield* api.request(`v1/pages/${page.id}/markdown`, { type: "replace_content", replace_content: { new_str: next } }, { method: "PATCH" });
3681
+ pageMarkdown(written);
3682
+ completed.push(stage);
3683
+ checkpoint = yield* openSkill(id, { refresh: true });
3684
+ }
3685
+ });
3686
+ for (const page of pages.slice(1))
3687
+ yield* writePage(page, bodies.get(page.path));
3688
+ yield* writePage(pages[0], doc.body);
3689
+ stage = "references";
3690
+ yield* checkVersion(checkpoint);
3691
+ yield* api.request(`v1/pages/${id}`, {
3692
+ properties: {
3693
+ [props.title]: { title: [{ text: { content: doc.name } }] },
3694
+ [props.description]: { rich_text: [{ text: { content: doc.description } }] },
3695
+ [props.references]: {
3696
+ rich_text: pages.slice(1).flatMap((page, index) => [
3697
+ ...index ? [{ type: "text", text: { content: `
3698
+ ` } }] : [],
3699
+ {
3700
+ type: "text",
3701
+ text: {
3702
+ content: page.path,
3703
+ link: { url: `https://www.notion.so/${page.id.replaceAll("-", "")}` }
3704
+ }
3705
+ }
3706
+ ])
3707
+ }
3708
+ }
3709
+ }, { method: "PATCH" });
3710
+ completed.push(stage);
3711
+ checkpoint = yield* openSkill(id, { refresh: true });
3712
+ if (props.files) {
3713
+ stage = "source_bundle";
3714
+ const main = checkpoint.files.find((file) => file.path === "SKILL.md");
3715
+ const store = yield* Store;
3716
+ const localDoc = importDocument({ path: "SKILL.md", bytes: yield* store.readBytes(`objects/${main.sha256}`) }, { name: doc.name, description: doc.description });
3717
+ const referenceProjection = {};
3718
+ for (const page of checkpoint.references?.slice(1) ?? []) {
3719
+ const file = checkpoint.files.find((file) => file.path === page.path);
3720
+ referenceProjection[page.path] = bodyIdentity(new TextDecoder().decode(yield* store.readBytes(`objects/${file.sha256}`)));
3721
+ }
3722
+ const bytes = yield* Effect10.try({
3723
+ try: () => portableZip({
3724
+ ...portable,
3725
+ projection: {
3726
+ name: doc.name,
3727
+ description: doc.description,
3728
+ body: bodyIdentity(localDoc.body),
3729
+ references: referenceProjection
3730
+ }
3731
+ }, true),
3732
+ catch: (error) => error
3733
+ });
3734
+ const bundle = yield* upload({ bytes }, BUNDLE);
3735
+ completed.push("upload:source_bundle");
3736
+ yield* checkVersion(checkpoint);
3737
+ yield* api.request(`v1/pages/${id}`, { properties: { [props.files]: { files: [bundle] } } }, { method: "PATCH" });
3738
+ completed.push(stage);
3739
+ }
3740
+ stage = "verify";
3741
+ const snapshot = yield* openSkill(id, { refresh: true });
3742
+ const saved = yield* snapshotPortable(snapshot);
3743
+ const savedId = yield* portableIdentity(saved);
3744
+ if (props.files ? savedId !== contentId : (yield* referenceContentIdentity(saved)) !== (yield* referenceContentIdentity(portable)))
3745
+ return yield* Effect10.fail(fail("WRITE_VERIFICATION_FAILED", "Saved reference pages or Skill files differ from the submitted content."));
3746
+ return {
3747
+ ...snapshotInfo(snapshot),
3748
+ operation,
3749
+ action: current ? "update" : "create",
3750
+ verified: true,
3751
+ content_id: savedId,
3752
+ reused: false,
3753
+ ...current ? { previous_version_id: current.version_id, expected_version_id: current.version_id } : {}
3754
+ };
3755
+ }).pipe(Effect10.mapError((error) => fail(error.code === "WRITE_OUTCOME_UNKNOWN" ? error.code : completed.length ? "WRITE_PARTIAL" : error.code, error.message, {
3756
+ ...source,
3757
+ ...id ? { page_id: id } : {},
3758
+ stage,
3759
+ completed,
3760
+ cause_code: error.code,
3761
+ cause_details: error.details
3762
+ })), Effect10.tapError((error) => id && (error.code === "WRITE_PARTIAL" || error.code === "WRITE_OUTCOME_UNKNOWN") ? invalidateSnapshotCache(id, current?.scope).pipe(Effect10.catch(() => Effect10.void)) : Effect10.void));
3763
+ });
3764
+ }
3765
+
3766
+ // packages/core/src/mutation.ts
3767
+ var DESCRIPTION = "notion%3A%2F%2Fskills%2Fdescription_property";
3768
+ var FILES = "notion%3A%2F%2Fskills%2Ffiles_property";
3769
+ var decoder4 = new TextDecoder("utf-8", { fatal: true });
3770
+ function skillDocument(bytes) {
2513
3771
  try {
2514
3772
  const content = decoder4.decode(bytes);
2515
3773
  const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(content);
@@ -2540,15 +3798,15 @@ function skillDocument(bytes) {
2540
3798
  }
2541
3799
  }
2542
3800
  function inputFile(input) {
2543
- return Effect7.gen(function* () {
3801
+ return Effect11.gen(function* () {
2544
3802
  const fs = yield* FileSystem4.FileSystem;
2545
3803
  const path = yield* Path4.Path;
2546
3804
  const full = path.resolve(input);
2547
3805
  const info = yield* fs.stat(full);
2548
3806
  if (info.type !== "File")
2549
- return yield* Effect7.fail(fail("INVALID_INPUT", "Input must be a regular file.", { input }));
3807
+ return yield* Effect11.fail(fail("INVALID_INPUT", "Input must be a regular file.", { input }));
2550
3808
  return { local: full, bytes: yield* fs.readFile(full) };
2551
- }).pipe(Effect7.mapError((error) => error instanceof SkillsError ? error : fail("INPUT_FAILED", "Could not read the input file.", { input })));
3809
+ }).pipe(Effect11.mapError((error) => error instanceof SkillsError ? error : fail("INPUT_FAILED", "Could not read the input file.", { input })));
2552
3810
  }
2553
3811
  function documentName(name) {
2554
3812
  return name.split("-").map((word) => word[0].toUpperCase() + word.slice(1)).join(" ");
@@ -2559,12 +3817,14 @@ function pageProperties(raw) {
2559
3817
  const title = values.find((p) => p.type === "title");
2560
3818
  const description = values.find((p) => p.id === DESCRIPTION) ?? property(properties.Description);
2561
3819
  const files = values.find((p) => p.id === FILES) ?? property(properties.Files);
2562
- if (typeof title?.id !== "string" || typeof description.id !== "string" || typeof files.id !== "string")
2563
- throw fail("INVALID_RESPONSE", "Skills Database must expose title, Description and Files properties.");
3820
+ const references = referencesProperty(raw);
3821
+ if (typeof title?.id !== "string" || typeof description.id !== "string" || !references && typeof files.id !== "string")
3822
+ throw fail("INVALID_RESPONSE", "Skill database must expose title, Description and References or Files properties.");
2564
3823
  return {
2565
3824
  title: title.id,
2566
3825
  description: description.id,
2567
- files: files.id,
3826
+ files: typeof files.id === "string" ? files.id : undefined,
3827
+ references: references ? String(references.id) : undefined,
2568
3828
  attachments: Array.isArray(files.files) ? files.files : []
2569
3829
  };
2570
3830
  }
@@ -2575,10 +3835,10 @@ function markdown(raw) {
2575
3835
  return value.markdown;
2576
3836
  }
2577
3837
  function upload(input, filename) {
2578
- return Effect7.gen(function* () {
3838
+ return Effect11.gen(function* () {
2579
3839
  const api = yield* Notion;
2580
3840
  if (input.bytes.length > 20 * 1024 * 1024)
2581
- return yield* Effect7.fail(fail("FILE_TOO_LARGE", "Direct upload supports files up to 20 MiB.", { path: filename }));
3841
+ return yield* Effect11.fail(fail("FILE_TOO_LARGE", "Direct upload supports files up to 20 MiB.", { path: filename }));
2582
3842
  const store = yield* Store;
2583
3843
  const path = yield* Path4.Path;
2584
3844
  const key = `uploads/${yield* sha256(input.bytes)}/${filename}`;
@@ -2588,22 +3848,32 @@ function upload(input, filename) {
2588
3848
  mode: "single_part"
2589
3849
  }));
2590
3850
  if (typeof raw.id !== "string")
2591
- return yield* Effect7.fail(fail("INVALID_RESPONSE", "File upload returned no ID."));
3851
+ return yield* Effect11.fail(fail("INVALID_RESPONSE", "File upload returned no ID."));
2592
3852
  const result = property(yield* api.request(`v1/file_uploads/${raw.id}/send`, undefined, {
2593
3853
  method: "POST",
2594
3854
  file: path.join(store.root, key)
2595
3855
  }));
2596
3856
  if (result.status !== "uploaded")
2597
- return yield* Effect7.fail(fail("INVALID_RESPONSE", "File upload has not completed.", { upload_id: raw.id }));
3857
+ return yield* Effect11.fail(fail("INVALID_RESPONSE", "File upload has not completed.", { upload_id: raw.id }));
2598
3858
  return { name: filename, type: "file_upload", file_upload: { id: raw.id } };
2599
3859
  });
2600
3860
  }
2601
3861
  function assertVersion(snapshot) {
2602
- return Effect7.gen(function* () {
3862
+ return Effect11.gen(function* () {
2603
3863
  const api = yield* Notion;
3864
+ if ("references" in snapshot && snapshot.references) {
3865
+ const latest = yield* openSkill(snapshot.skill.id, { refresh: true });
3866
+ if (latest.version_id !== snapshot.version_id)
3867
+ return yield* Effect11.fail(fail("WRITE_CONFLICT", "The skill or a reference page changed; read it again before writing.", {
3868
+ page_id: snapshot.skill.id,
3869
+ expected_version: snapshot.version_id,
3870
+ actual_version: latest.version_id
3871
+ }));
3872
+ return;
3873
+ }
2604
3874
  const latest = decode(ExportSchema, yield* api.request(`v1/ai/skills/${snapshot.skill.id}`));
2605
3875
  if (latest.id !== snapshot.skill.id || latest.version_id !== snapshot.version_id)
2606
- return yield* Effect7.fail(fail("WRITE_CONFLICT", "The remote skill changed; read it again before writing.", {
3876
+ return yield* Effect11.fail(fail("WRITE_CONFLICT", "The remote skill changed; read it again before writing.", {
2607
3877
  page_id: snapshot.skill.id,
2608
3878
  expected_version: snapshot.version_id,
2609
3879
  actual_version: latest.version_id
@@ -2611,58 +3881,58 @@ function assertVersion(snapshot) {
2611
3881
  });
2612
3882
  }
2613
3883
  function verifyFiles(snapshot, expected) {
2614
- return Effect7.gen(function* () {
3884
+ return Effect11.gen(function* () {
2615
3885
  for (const file of expected) {
2616
3886
  const actual = snapshot.files.find((item) => item.path === file.path);
2617
3887
  if (!actual || actual.sha256 !== (yield* sha256(file.bytes)))
2618
- return yield* Effect7.fail(fail("WRITE_VERIFICATION_FAILED", "Exported attachment differs from the submitted file.", { path: file.path }));
3888
+ return yield* Effect11.fail(fail("WRITE_VERIFICATION_FAILED", "Exported attachment differs from the submitted file.", { path: file.path }));
2619
3889
  }
2620
3890
  });
2621
3891
  }
2622
3892
  function verifyBody(snapshot, expected) {
2623
- return Effect7.gen(function* () {
3893
+ return Effect11.gen(function* () {
2624
3894
  const store = yield* Store;
2625
3895
  const entrypoint = snapshot.files.find((f) => f.path === "SKILL.md");
2626
3896
  const bytes = yield* store.readBytes(`objects/${entrypoint.sha256}`);
2627
- const exported = yield* Effect7.try({
3897
+ const exported = yield* Effect11.try({
2628
3898
  try: () => skillDocument(bytes),
2629
3899
  catch: (e) => e
2630
3900
  });
2631
3901
  if (bodyIdentity(exported.body) !== bodyIdentity(expected))
2632
- return yield* Effect7.fail(fail("WRITE_VERIFICATION_FAILED", "Exported Skill body differs from page Markdown."));
3902
+ return yield* Effect11.fail(fail("WRITE_VERIFICATION_FAILED", "Exported Skill body differs from page Markdown."));
2633
3903
  });
2634
3904
  }
2635
3905
  function writeSkill(inputTarget, options) {
2636
- return Effect7.gen(function* () {
2637
- const target = yield* Effect7.try({
3906
+ return Effect11.gen(function* () {
3907
+ const target = yield* Effect11.try({
2638
3908
  try: () => parseTarget(inputTarget, options.path),
2639
3909
  catch: (e) => e
2640
3910
  });
2641
3911
  const baseline = target.snapshot ? yield* targetSnapshot(target, options) : undefined;
2642
3912
  if (baseline && baseline.scope !== (yield* authScope))
2643
- return yield* Effect7.fail(fail("SNAPSHOT_CONFLICT", "The snapshot belongs to another authentication scope."));
3913
+ return yield* Effect11.fail(fail("SNAPSHOT_CONFLICT", "The snapshot belongs to another authentication scope."));
2644
3914
  const current = yield* openSkill(baseline?.skill.id ?? target.selector, {
2645
3915
  database: options.database,
2646
3916
  refresh: true
2647
3917
  });
2648
3918
  if (baseline && baseline.version_id !== current.version_id)
2649
- return yield* Effect7.fail(fail("WRITE_CONFLICT", "The remote Skill changed since the pinned read.", {
3919
+ return yield* Effect11.fail(fail("WRITE_CONFLICT", "The remote Skill changed since the pinned read.", {
2650
3920
  page_id: current.skill.id,
2651
3921
  expected_version: baseline.version_id,
2652
3922
  actual_version: current.version_id
2653
3923
  }));
2654
3924
  const path = target.path || "SKILL.md";
2655
3925
  if (path === BUNDLE || path === MANIFEST)
2656
- return yield* Effect7.fail(fail("INVALID_PATH", "The target is a reserved portability file.", { path }));
3926
+ return yield* Effect11.fail(fail("INVALID_PATH", "The target is a reserved portability file.", { path }));
2657
3927
  const input = yield* inputFile(options.input);
2658
3928
  const portable = yield* snapshotPortable(current);
2659
3929
  const sourcePath = path === "SKILL.md" ? portable.main : path;
2660
- const doc = path === "SKILL.md" ? yield* Effect7.try({
3930
+ const doc = path === "SKILL.md" ? yield* Effect11.try({
2661
3931
  try: () => skillDocument(input.bytes),
2662
3932
  catch: (e) => e
2663
3933
  }) : undefined;
2664
3934
  if (doc?.page_id && doc.page_id !== current.skill.id)
2665
- return yield* Effect7.fail(fail("SNAPSHOT_CONFLICT", "SKILL.md notion_page_id belongs to another Skill."));
3935
+ return yield* Effect11.fail(fail("SNAPSHOT_CONFLICT", "SKILL.md notion_page_id belongs to another Skill."));
2666
3936
  const name = doc ? doc.name === current.skill.alias ? current.skill.name : documentName(doc.name) : current.skill.name;
2667
3937
  const next = {
2668
3938
  ...portable,
@@ -2708,10 +3978,20 @@ function createSkill(input, options = {}) {
2708
3978
  function importSkill(input, options = {}) {
2709
3979
  return saveInput(input, options, "import");
2710
3980
  }
3981
+ function importPortable(portable, baseline, options = {}) {
3982
+ return saveDocument(portable, options, "import", baseline);
3983
+ }
2711
3984
  function saveInput(input, options, operation) {
2712
- return Effect7.gen(function* () {
3985
+ return Effect11.gen(function* () {
3986
+ const target = options.target !== undefined ? yield* Effect11.try({
3987
+ try: () => parseTarget(options.target),
3988
+ catch: (error) => error
3989
+ }) : undefined;
3990
+ if (target?.path && target.path !== "SKILL.md")
3991
+ return yield* Effect11.fail(fail("INVALID_ARGUMENT", "Whole-Skill import requires a main-file or pathless target."));
3992
+ const baseline = target ? target.snapshot ? yield* targetSnapshot(target, { database: options.database }) : yield* openSkill(target.selector, { database: options.database, refresh: true }) : undefined;
2713
3993
  const loaded = yield* loadImport(input);
2714
- const source = yield* Effect7.try({
3994
+ const source = yield* Effect11.try({
2715
3995
  try: () => {
2716
3996
  const portable = readPortable(importFiles(loaded.files, loaded.kind === "markdown"));
2717
3997
  const entry = portable ? {
@@ -2734,16 +4014,16 @@ function saveInput(input, options, operation) {
2734
4014
  catch: (e) => e
2735
4015
  });
2736
4016
  return {
2737
- ...yield* saveDocument(source, options, operation),
4017
+ ...yield* saveDocument(source, options, operation, baseline),
2738
4018
  input_type: loaded.kind,
2739
4019
  main_path: source.main
2740
4020
  };
2741
4021
  });
2742
4022
  }
2743
4023
  function saveDocument(portable, options, operation, baseline) {
2744
- return Effect7.gen(function* () {
4024
+ return Effect11.gen(function* () {
2745
4025
  const contentId = yield* portableIdentity(portable);
2746
- const doc = yield* Effect7.try({
4026
+ const doc = yield* Effect11.try({
2747
4027
  try: () => {
2748
4028
  portableZip(portable);
2749
4029
  return importDocument(portable.files.find((file) => file.path === portable.main), {
@@ -2754,58 +4034,75 @@ function saveDocument(portable, options, operation, baseline) {
2754
4034
  catch: (e) => e
2755
4035
  });
2756
4036
  let current = baseline;
4037
+ if (baseline) {
4038
+ if (baseline.scope !== (yield* authScope))
4039
+ return yield* Effect11.fail(fail("SNAPSHOT_CONFLICT", "The snapshot belongs to another authentication scope."));
4040
+ current = yield* openSkill(baseline.skill.id, { database: options.database, refresh: true });
4041
+ if (current.version_id !== baseline.version_id || current.skill.database_id !== baseline.skill.database_id || current.skill.data_source_id !== baseline.skill.data_source_id)
4042
+ return yield* Effect11.fail(fail("WRITE_CONFLICT", "The remote Skill changed since the expected baseline.", {
4043
+ page_id: baseline.skill.id,
4044
+ expected_version: baseline.version_id,
4045
+ actual_version: current.version_id
4046
+ }));
4047
+ }
2757
4048
  let databaseId = current?.skill.database_id;
2758
4049
  let dataSourceId = current?.skill.data_source_id;
2759
4050
  if (!current) {
2760
4051
  const source = yield* creationSource(options.database);
2761
4052
  databaseId = source.database_id;
2762
4053
  if (source.data_source_ids.length !== 1)
2763
- return yield* Effect7.fail(fail("DATABASE_AMBIGUOUS", "Skills Database must have exactly one data source.", {
4054
+ return yield* Effect11.fail(fail("DATABASE_AMBIGUOUS", "Skills Database must have exactly one data source.", {
2764
4055
  source
2765
4056
  }));
2766
4057
  dataSourceId = source.data_source_ids[0];
2767
4058
  const directory = yield* catalog({ database: databaseId, refresh: true });
2768
4059
  if (directory.coverage.failed_sources.length)
2769
- return yield* Effect7.fail(fail("CATALOG_INCOMPLETE", "Cannot prove Skill name uniqueness.", directory.coverage));
4060
+ return yield* Effect11.fail(fail("CATALOG_INCOMPLETE", "Cannot prove Skill name uniqueness.", directory.coverage));
2770
4061
  const matches = directory.skills.filter((skill) => skill.alias === aliasFor(doc.name));
2771
4062
  if (matches.length > 1)
2772
- return yield* Effect7.fail(fail("SKILL_AMBIGUOUS", "Multiple pages share this invocation name.", {
4063
+ return yield* Effect11.fail(fail("SKILL_AMBIGUOUS", "Multiple pages share this invocation name.", {
2773
4064
  candidates: matches,
2774
4065
  databases: directory.databases
2775
4066
  }));
2776
4067
  if (matches[0]) {
2777
4068
  if (operation === "create")
2778
- return yield* Effect7.fail(fail("CREATE_CONFLICT", "A Skill with this invocation name already exists; use import to replace it.", {
4069
+ return yield* Effect11.fail(fail("CREATE_CONFLICT", "A Skill with this invocation name already exists; use import to replace it.", {
2779
4070
  page_id: matches[0].id,
2780
4071
  name: doc.name,
2781
4072
  database_id: databaseId,
2782
4073
  data_source_id: dataSourceId
2783
4074
  }));
2784
4075
  current = yield* openSkill(matches[0].id, { refresh: true });
2785
- if ((yield* portableIdentity(yield* snapshotPortable(current))) === contentId) {
2786
- yield* assertVersion(current);
2787
- return {
2788
- ...snapshotInfo(current),
2789
- operation,
2790
- action: "reuse",
2791
- reused: true,
2792
- content_id: contentId,
2793
- verified: true,
2794
- ...options.dryRun ? { dry_run: true } : {}
2795
- };
2796
- }
2797
4076
  }
2798
4077
  }
2799
4078
  const api = yield* Notion;
2800
4079
  const raw = yield* api.request(current ? `v1/pages/${current.skill.id}` : `v1/data_sources/${dataSourceId}`);
2801
- const props = yield* Effect7.try({
4080
+ const props = yield* Effect11.try({
2802
4081
  try: () => pageProperties(raw),
2803
4082
  catch: (e) => e
2804
4083
  });
4084
+ if (current && operation === "import") {
4085
+ const saved = yield* snapshotPortable(current);
4086
+ const same = props.references && !props.files ? (yield* referenceContentIdentity(saved)) === (yield* referenceContentIdentity(portable)) : (yield* portableIdentity(saved)) === contentId;
4087
+ if (same) {
4088
+ yield* assertVersion(current);
4089
+ return {
4090
+ ...snapshotInfo(current),
4091
+ operation,
4092
+ action: "reuse",
4093
+ reused: true,
4094
+ content_id: yield* portableIdentity(saved),
4095
+ previous_version_id: current.version_id,
4096
+ expected_version_id: baseline?.version_id ?? current.version_id,
4097
+ verified: true,
4098
+ ...options.dryRun ? { dry_run: true } : {}
4099
+ };
4100
+ }
4101
+ }
2805
4102
  let oldBody = "";
2806
4103
  if (current) {
2807
4104
  const rawBody = yield* api.request(`v1/pages/${current.skill.id}/markdown`);
2808
- oldBody = yield* Effect7.try({ try: () => markdown(rawBody), catch: (e) => e });
4105
+ oldBody = yield* Effect11.try({ try: () => markdown(rawBody), catch: (e) => e });
2809
4106
  }
2810
4107
  const action = current ? "update" : "create";
2811
4108
  const plan = {
@@ -2820,17 +4117,29 @@ function saveDocument(portable, options, operation, baseline) {
2820
4117
  ...current ? {
2821
4118
  page_id: current.skill.id,
2822
4119
  base_version_id: current.version_id,
4120
+ previous_version_id: current.version_id,
4121
+ expected_version_id: baseline?.version_id ?? current.version_id,
2823
4122
  snapshot_id: current.snapshot_id,
2824
4123
  ref: snapshotInfo(current).ref
2825
4124
  } : {},
2826
4125
  files: portable.files.map((file) => ({ path: file.path, bytes: file.bytes.length }))
2827
4126
  };
2828
- if (options.dryRun)
4127
+ if (options.dryRun) {
4128
+ if (props.references)
4129
+ yield* referenceInput(portable, Boolean(props.files));
2829
4130
  return { ...plan, dry_run: true };
4131
+ }
4132
+ if (props.references)
4133
+ return yield* saveReferences(portable, doc, {
4134
+ title: props.title,
4135
+ description: props.description,
4136
+ references: props.references,
4137
+ files: props.files
4138
+ }, { database_id: databaseId, data_source_id: dataSourceId }, operation, current, upload);
2830
4139
  const completed = [];
2831
4140
  let id = current?.skill.id;
2832
4141
  let stage = "prepare";
2833
- return yield* Effect7.gen(function* () {
4142
+ return yield* Effect11.gen(function* () {
2834
4143
  if (current)
2835
4144
  yield* assertVersion(current);
2836
4145
  else {
@@ -2843,7 +4152,7 @@ function saveDocument(portable, options, operation, baseline) {
2843
4152
  }
2844
4153
  });
2845
4154
  completed.push(stage);
2846
- id = yield* Effect7.try({
4155
+ id = yield* Effect11.try({
2847
4156
  try: () => decode(PageSchema, created).id,
2848
4157
  catch: (e) => e
2849
4158
  });
@@ -2856,18 +4165,18 @@ function saveDocument(portable, options, operation, baseline) {
2856
4165
  update_content: { content_updates: [{ old_str: oldBody, new_str: doc.body }] }
2857
4166
  } : { type: "replace_content", replace_content: { new_str: doc.body } }, { method: "PATCH" });
2858
4167
  completed.push(stage);
2859
- expectedBody = yield* Effect7.try({
4168
+ expectedBody = yield* Effect11.try({
2860
4169
  try: () => markdown(written),
2861
4170
  catch: (e) => e
2862
4171
  });
2863
4172
  }
2864
4173
  const exportedVersion = yield* api.request(`v1/ai/skills/${id}`);
2865
- const beforeUpload = yield* Effect7.try({
4174
+ const beforeUpload = yield* Effect11.try({
2866
4175
  try: () => decode(ExportSchema, exportedVersion),
2867
4176
  catch: (e) => e
2868
4177
  });
2869
4178
  stage = "source_bundle";
2870
- const bytes = yield* Effect7.try({
4179
+ const bytes = yield* Effect11.try({
2871
4180
  try: () => portableZip({
2872
4181
  ...portable,
2873
4182
  projection: {
@@ -2893,18 +4202,18 @@ function saveDocument(portable, options, operation, baseline) {
2893
4202
  stage = "verify_export";
2894
4203
  const snapshot = yield* openSkill(id, { refresh: true });
2895
4204
  if (snapshot.skill.name !== doc.name || snapshot.skill.description !== doc.description)
2896
- return yield* Effect7.fail(fail("WRITE_VERIFICATION_FAILED", "Skill metadata differs from the submitted values."));
4205
+ return yield* Effect11.fail(fail("WRITE_VERIFICATION_FAILED", "Skill metadata differs from the submitted values."));
2897
4206
  yield* verifyFiles(snapshot, [{ path: BUNDLE, bytes }]);
2898
4207
  const readback = yield* api.request(`v1/pages/${id}/markdown`);
2899
- const body = yield* Effect7.try({
4208
+ const body = yield* Effect11.try({
2900
4209
  try: () => markdown(readback),
2901
4210
  catch: (e) => e
2902
4211
  });
2903
4212
  if (body !== expectedBody)
2904
- return yield* Effect7.fail(fail("WRITE_VERIFICATION_FAILED", "Page Markdown changed during verification."));
4213
+ return yield* Effect11.fail(fail("WRITE_VERIFICATION_FAILED", "Page Markdown changed during verification."));
2905
4214
  yield* verifyBody(snapshot, body);
2906
4215
  if ((yield* portableIdentity(yield* snapshotPortable(snapshot))) !== contentId)
2907
- return yield* Effect7.fail(fail("WRITE_VERIFICATION_FAILED", "Saved Skill files differ from the submitted content."));
4216
+ return yield* Effect11.fail(fail("WRITE_VERIFICATION_FAILED", "Saved Skill files differ from the submitted content."));
2908
4217
  return {
2909
4218
  ...snapshotInfo(snapshot),
2910
4219
  operation,
@@ -2912,27 +4221,1462 @@ function saveDocument(portable, options, operation, baseline) {
2912
4221
  verified: true,
2913
4222
  content_id: contentId,
2914
4223
  reused: false,
2915
- ...current ? { previous_version_id: current.version_id } : {}
4224
+ ...current ? {
4225
+ previous_version_id: current.version_id,
4226
+ expected_version_id: baseline?.version_id ?? current.version_id
4227
+ } : {}
2916
4228
  };
2917
- }).pipe(Effect7.mapError((error) => fail(error.code === "WRITE_OUTCOME_UNKNOWN" ? error.code : completed.length ? "WRITE_PARTIAL" : error.code, error.message, {
4229
+ }).pipe(Effect11.mapError((error) => fail(error.code === "WRITE_OUTCOME_UNKNOWN" ? error.code : completed.length ? "WRITE_PARTIAL" : error.code, error.message, {
2918
4230
  database_id: databaseId,
2919
4231
  ...id ? { page_id: id } : {},
2920
4232
  stage,
2921
4233
  completed,
2922
4234
  cause_code: error.code,
2923
4235
  cause_details: error.details
2924
- })));
4236
+ })), Effect11.tapError((error) => id && (error.code === "WRITE_PARTIAL" || error.code === "WRITE_OUTCOME_UNKNOWN") ? invalidateSnapshotCache(id, current?.scope).pipe(Effect11.catch(() => Effect11.void)) : Effect11.void));
4237
+ });
4238
+ }
4239
+ // packages/core/src/sync-local.ts
4240
+ import { Context as Context3, Effect as Effect12, Layer as Layer3 } from "effect";
4241
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
4242
+ import * as fs2 from "node:fs/promises";
4243
+ import * as path2 from "node:path";
4244
+ class SyncLocal extends Context3.Service()("ntn-skills/SyncLocal") {
4245
+ }
4246
+ var digest = (bytes) => createHash2("sha256").update(bytes).digest("hex");
4247
+ var equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
4248
+ var missing = (error) => error !== null && typeof error === "object" && ("code" in error) && error.code === "ENOENT";
4249
+ var safeError = (error) => {
4250
+ if (error instanceof SkillsError)
4251
+ return error;
4252
+ const code = error !== null && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : undefined;
4253
+ return fail("LOCAL_IO_ERROR", "Local filesystem operation failed.", { syscall_code: code });
4254
+ };
4255
+ var attempt = (run) => Effect12.tryPromise({ try: run, catch: safeError });
4256
+ async function resolveProof(input, allowMissing, allowDangling = false) {
4257
+ const absolute = path2.resolve(input);
4258
+ let pending = absolute.split(path2.sep).filter(Boolean).map((component) => ({ component, required: false }));
4259
+ let current = path2.parse(absolute).root;
4260
+ const nodes = [];
4261
+ const rootInfo = await fs2.lstat(current, { bigint: true });
4262
+ nodes.push({
4263
+ path: current,
4264
+ kind: "directory",
4265
+ dev: String(rootInfo.dev),
4266
+ ino: String(rootInfo.ino)
4267
+ });
4268
+ let hops = 0;
4269
+ while (pending.length) {
4270
+ const { component, required } = pending.shift();
4271
+ if (component === ".")
4272
+ continue;
4273
+ if (component === "..") {
4274
+ current = path2.dirname(current);
4275
+ continue;
4276
+ }
4277
+ const next = path2.join(current, component);
4278
+ let info;
4279
+ try {
4280
+ info = await fs2.lstat(next, { bigint: true });
4281
+ } catch (error) {
4282
+ if (!missing(error))
4283
+ throw error;
4284
+ if (required && !allowDangling)
4285
+ throw fail("LOCAL_LINK_BROKEN", "A local symbolic link is dangling.", { path: next });
4286
+ if (!allowMissing)
4287
+ throw fail("LOCAL_MISSING", "The local Skill directory or file is missing.", { path: next });
4288
+ return {
4289
+ nodes,
4290
+ resolved_path: path2.join(next, ...pending.map((item) => item.component)),
4291
+ exists: false
4292
+ };
4293
+ }
4294
+ const kind = info.isSymbolicLink() ? "link" : info.isDirectory() ? "directory" : info.isFile() ? "file" : undefined;
4295
+ if (!kind)
4296
+ throw fail("INVALID_PATH", "Local Skill paths must be ordinary files, directories or symbolic links.", { path: next });
4297
+ if (kind === "link") {
4298
+ if (++hops > 40)
4299
+ throw fail("LOCAL_LINK_CYCLE", "The local symbolic link chain is cyclic or too deep.", {
4300
+ path: next
4301
+ });
4302
+ const link = await fs2.readlink(next);
4303
+ nodes.push({ path: next, kind, dev: String(info.dev), ino: String(info.ino), link });
4304
+ const targetParts = link.split(path2.sep).filter(Boolean);
4305
+ pending = [...targetParts.map((component) => ({ component, required: true })), ...pending];
4306
+ if (path2.isAbsolute(link))
4307
+ current = path2.parse(link).root;
4308
+ continue;
4309
+ }
4310
+ nodes.push({ path: next, kind, dev: String(info.dev), ino: String(info.ino) });
4311
+ if (pending.length && kind !== "directory")
4312
+ throw fail("INVALID_PATH", "A local parent is not a directory.", { path: next });
4313
+ current = next;
4314
+ }
4315
+ return { nodes, resolved_path: current, exists: true };
4316
+ }
4317
+ function validRelative(input) {
4318
+ if (!input || normalizePath(input) !== input || input.split("/").some((part) => part.startsWith(".")) && input !== MANIFEST)
4319
+ throw fail("INVALID_PATH", "Sync requires normalized non-hidden portable file paths.", {
4320
+ path: input
4321
+ });
4322
+ return input;
4323
+ }
4324
+ function makeSyncLocal(options = {}) {
4325
+ const stateRoot = path2.resolve(options.stateRoot ?? process.env.NTN_SKILLS_HOME ?? path2.join(process.env.XDG_STATE_HOME ?? path2.join(process.env.HOME ?? process.env.USERPROFILE ?? ".", ".local", "state"), "ntn-skills"));
4326
+ const trash = options.trash ?? retainInTrash;
4327
+ const inspect = async (logicalPath, inspectOptions = {}) => {
4328
+ const logical = path2.resolve(logicalPath);
4329
+ const root = await resolveProof(logical, !!inspectOptions.allowMissing);
4330
+ if (!root.exists) {
4331
+ const parent = await resolveProof(path2.dirname(logical), false);
4332
+ if (parent.nodes.at(-1)?.kind !== "directory")
4333
+ throw fail("INVALID_PATH", "The local parent must be a directory.");
4334
+ return {
4335
+ logical_path: logical,
4336
+ resolved_path: root.resolved_path,
4337
+ exists: false,
4338
+ proof: { root, files: [] },
4339
+ file_hashes: []
4340
+ };
4341
+ }
4342
+ if (root.nodes.at(-1)?.kind !== "directory")
4343
+ throw fail("INVALID_PATH", "The bound local path must be a directory.", { path: logical });
4344
+ const selected = new Set;
4345
+ const directories = new Set;
4346
+ const proofs = new Map;
4347
+ const walk = async (relative, ancestors = []) => {
4348
+ const location = path2.join(logical, relative);
4349
+ const proof = await resolveProof(location, true);
4350
+ proofs.set(relative, proof);
4351
+ if (!proof.exists)
4352
+ return;
4353
+ if (proof.nodes.at(-1)?.kind === "directory") {
4354
+ if (ancestors.includes(proof.resolved_path))
4355
+ throw fail("LOCAL_LINK_CYCLE", "A local directory link creates a traversal cycle.", {
4356
+ path: location
4357
+ });
4358
+ directories.add(relative);
4359
+ for (const child of (await fs2.readdir(proof.resolved_path)).sort()) {
4360
+ if (child.startsWith("."))
4361
+ continue;
4362
+ await walk(relative ? `${relative}/${child}` : child, [...ancestors, proof.resolved_path]);
4363
+ }
4364
+ } else
4365
+ selected.add(relative);
4366
+ };
4367
+ if (inspectOptions.trackedPaths === undefined) {
4368
+ for (const child of (await fs2.readdir(root.resolved_path)).sort())
4369
+ if (!child.startsWith("."))
4370
+ await walk(child, [root.resolved_path]);
4371
+ } else {
4372
+ for (const relative of [...new Set(inspectOptions.trackedPaths)].sort())
4373
+ await walk(validRelative(relative), [root.resolved_path]);
4374
+ const owned = new Set([
4375
+ "references",
4376
+ "assets",
4377
+ "scripts",
4378
+ "templates",
4379
+ ...inspectOptions.trackedPaths.filter((entry) => entry.includes("/")).map((entry) => entry.split("/")[0])
4380
+ ]);
4381
+ for (const directory of [...owned].sort())
4382
+ await walk(validRelative(directory), [root.resolved_path]);
4383
+ }
4384
+ await walk(MANIFEST, [root.resolved_path]);
4385
+ const files = [];
4386
+ let totalBytes = 0;
4387
+ for (const relative of [...selected].sort()) {
4388
+ const proof = proofs.get(relative);
4389
+ const bytes = await fs2.readFile(proof.resolved_path);
4390
+ if (!equal(proof, await resolveProof(path2.join(logical, relative), false)))
4391
+ throw fail("SYNC_TARGET_DRIFT", "A local destination changed while it was being inspected.", { path: relative });
4392
+ files.push({ path: relative, bytes });
4393
+ totalBytes += bytes.length;
4394
+ if (files.length > 1e4 || totalBytes > 128 * 1024 * 1024)
4395
+ throw fail("ARCHIVE_TOO_LARGE", "Local Skill exceeds 128 MiB or 10,000 files.");
4396
+ }
4397
+ if (!equal(root, await resolveProof(logical, false)))
4398
+ throw fail("SYNC_TARGET_DRIFT", "The local directory changed during inspection.");
4399
+ let content = readPortable(files);
4400
+ if (!content) {
4401
+ const main = files.find((file) => file.path === "SKILL.md");
4402
+ if (!main)
4403
+ throw fail("LOCAL_MISSING", "The local Skill entrypoint is missing.", { path: logical });
4404
+ const metadata = importDocument(main);
4405
+ content = { name: metadata.name, description: metadata.description, main: main.path, files };
4406
+ }
4407
+ const file_hashes = files.map((file) => ({
4408
+ path: file.path,
4409
+ bytes: file.bytes.length,
4410
+ sha256: digest(file.bytes)
4411
+ }));
4412
+ const content_id = digest(JSON.stringify({
4413
+ name: content.name,
4414
+ description: content.description,
4415
+ main: content.main,
4416
+ files: file_hashes.filter((file) => file.path !== MANIFEST)
4417
+ }));
4418
+ return {
4419
+ logical_path: logical,
4420
+ resolved_path: root.resolved_path,
4421
+ exists: true,
4422
+ proof: {
4423
+ root,
4424
+ files: [...proofs].filter(([relative, proof]) => proof.exists && (!directories.has(relative) || ["references", "assets", "scripts", "templates"].includes(relative))).sort(([a], [b]) => a.localeCompare(b)).map(([relative, proof]) => ({ path: relative, proof }))
4425
+ },
4426
+ content,
4427
+ content_id,
4428
+ file_hashes
4429
+ };
4430
+ };
4431
+ const commit = async (expected, content, trackedPaths, operationId) => {
4432
+ const incoming = portableFiles(content);
4433
+ for (const file of incoming)
4434
+ validRelative(file.path);
4435
+ const tracked = [
4436
+ ...new Set([...trackedPaths, ...expected.file_hashes.map((file) => file.path), MANIFEST])
4437
+ ].map(validRelative);
4438
+ if (!options.trash) {
4439
+ if (process.platform !== "darwin")
4440
+ throw fail("RETENTION_UNAVAILABLE", "System Trash is required before local commit.");
4441
+ try {
4442
+ await fs2.access("/usr/bin/trash", fs2.constants.X_OK);
4443
+ } catch {
4444
+ throw fail("RETENTION_UNAVAILABLE", "The /usr/bin/trash capability is required before local commit.");
4445
+ }
4446
+ }
4447
+ const current = await inspect(expected.logical_path, {
4448
+ allowMissing: !expected.exists,
4449
+ ...expected.exists ? { trackedPaths } : {}
4450
+ });
4451
+ if (!equal(current.proof, expected.proof) || current.content_id !== expected.content_id || !equal(current.file_hashes, expected.file_hashes))
4452
+ throw fail("SYNC_PLAN_STALE", "Local content or destination no longer matches the saved inspection.");
4453
+ const scratch = path2.join(stateRoot, "sync", "staging", `${digest(operationId)}-${randomUUID2()}`);
4454
+ await fs2.mkdir(scratch, { recursive: true, mode: 448 });
4455
+ const retained = [
4456
+ { path: scratch, retention_path: scratch }
4457
+ ];
4458
+ const completed = [];
4459
+ const allPaths = [...new Set([...tracked, ...incoming.map((file) => file.path)])].sort();
4460
+ let rootProof = expected.proof.root;
4461
+ let guarded = new Map;
4462
+ const retiredLinks = new Set;
4463
+ const immutable = new Map;
4464
+ for (const proof of [
4465
+ expected.proof.root,
4466
+ ...expected.proof.files.map((entry) => entry.proof)
4467
+ ]) {
4468
+ for (const node of proof.nodes)
4469
+ if (node.kind !== "file")
4470
+ immutable.set(node.path, node);
4471
+ }
4472
+ const checkImmutable = async () => {
4473
+ for (const [location, node] of immutable) {
4474
+ if (retiredLinks.has(location))
4475
+ continue;
4476
+ const info = await fs2.lstat(location, { bigint: true });
4477
+ const link = node.kind === "link" ? await fs2.readlink(location) : undefined;
4478
+ if (String(info.dev) !== node.dev || String(info.ino) !== node.ino || (node.kind === "link" ? !info.isSymbolicLink() || link !== node.link : !info.isDirectory()))
4479
+ throw fail("SYNC_TARGET_DRIFT", "An original parent or link identity changed during commit.", { path: location });
4480
+ }
4481
+ };
4482
+ const capture = async (changedPath) => {
4483
+ await checkImmutable();
4484
+ const nextRoot = await resolveProof(expected.logical_path, true, true);
4485
+ if (rootProof.exists && !equal(rootProof, nextRoot))
4486
+ throw fail("SYNC_TARGET_DRIFT", "The root changed during a local syscall.");
4487
+ const nextGuarded = new Map;
4488
+ if (nextRoot.exists)
4489
+ for (const relative of allPaths) {
4490
+ const proof = await resolveProof(path2.join(expected.logical_path, relative), true, true);
4491
+ const hash = proof.exists && proof.nodes.at(-1)?.kind === "file" ? digest(await fs2.readFile(proof.resolved_path)) : undefined;
4492
+ const previous = guarded.get(relative);
4493
+ if (previous?.hash !== undefined && previous.proof.resolved_path !== changedPath && hash !== previous.hash)
4494
+ throw fail("SYNC_TARGET_DRIFT", "An unrelated tracked file changed during a local syscall.", { path: relative });
4495
+ nextGuarded.set(relative, { proof, ...hash === undefined ? {} : { hash } });
4496
+ for (const node of proof.nodes)
4497
+ if (node.kind !== "file")
4498
+ immutable.set(node.path, node);
4499
+ }
4500
+ for (const node of nextRoot.nodes)
4501
+ if (node.kind !== "file")
4502
+ immutable.set(node.path, node);
4503
+ rootProof = nextRoot;
4504
+ guarded = nextGuarded;
4505
+ };
4506
+ const guard = async (kind, location) => {
4507
+ await options.beforeBoundary?.({ kind, path: location, operation_id: operationId });
4508
+ await checkImmutable();
4509
+ if (!equal(rootProof, await resolveProof(expected.logical_path, true, true)))
4510
+ throw fail("SYNC_TARGET_DRIFT", "The local root or parent link changed at commit.", {
4511
+ path: location
4512
+ });
4513
+ for (const [relative, entry] of guarded) {
4514
+ const proof = await resolveProof(path2.join(expected.logical_path, relative), true, true);
4515
+ if (!equal(proof, entry.proof) || entry.hash !== undefined && digest(await fs2.readFile(proof.resolved_path)) !== entry.hash)
4516
+ throw fail("SYNC_TARGET_DRIFT", "A local file target or content changed at commit.", {
4517
+ path: relative
4518
+ });
4519
+ }
4520
+ };
4521
+ try {
4522
+ for (let index = 0;index < incoming.length; index++)
4523
+ await fs2.writeFile(path2.join(scratch, String(index)), incoming[index].bytes, {
4524
+ flag: "wx",
4525
+ mode: 384
4526
+ });
4527
+ const restaged = await inspect(expected.logical_path, {
4528
+ allowMissing: !expected.exists,
4529
+ ...expected.exists ? { trackedPaths } : {}
4530
+ });
4531
+ if (!equal(restaged.proof, expected.proof) || !equal(restaged.file_hashes, expected.file_hashes))
4532
+ throw fail("SYNC_TARGET_DRIFT", "The local target changed while content was staged.");
4533
+ const destinations = new Map;
4534
+ for (const file of incoming) {
4535
+ const proof = await resolveProof(path2.join(expected.logical_path, file.path), true);
4536
+ if (proof.exists && !expected.file_hashes.some((entry) => entry.path === file.path))
4537
+ throw fail("OUTPUT_CONFLICT", "Incoming portable content collides with an unrelated local file.", { path: file.path });
4538
+ const previous = destinations.get(proof.resolved_path);
4539
+ if (previous !== undefined)
4540
+ throw fail("INVALID_PATH", "Two portable files resolve to the same actual destination.", {
4541
+ paths: [previous, file.path]
4542
+ });
4543
+ destinations.set(proof.resolved_path, file.path);
4544
+ }
4545
+ await capture();
4546
+ if (!expected.exists) {
4547
+ await guard("mkdir", expected.resolved_path);
4548
+ await fs2.mkdir(expected.resolved_path, { mode: 448 });
4549
+ await capture();
4550
+ }
4551
+ for (const relative of allPaths) {
4552
+ const fileIndex = incoming.findIndex((file) => file.path === relative);
4553
+ const desired = fileIndex < 0 ? undefined : incoming[fileIndex];
4554
+ const proof = await resolveProof(path2.join(expected.logical_path, relative), true);
4555
+ if (!proof.exists && !desired)
4556
+ continue;
4557
+ if (proof.exists && proof.nodes.at(-1)?.kind !== "file")
4558
+ throw fail("INVALID_PATH", "A portable destination is not an ordinary file.", {
4559
+ path: relative
4560
+ });
4561
+ if (desired && proof.exists && digest(desired.bytes) === guarded.get(relative)?.hash)
4562
+ continue;
4563
+ const destination = proof.resolved_path;
4564
+ const missingParents = [];
4565
+ let parent = path2.dirname(destination);
4566
+ while (true) {
4567
+ try {
4568
+ await fs2.lstat(parent);
4569
+ break;
4570
+ } catch (error) {
4571
+ if (!missing(error))
4572
+ throw error;
4573
+ missingParents.unshift(parent);
4574
+ parent = path2.dirname(parent);
4575
+ }
4576
+ }
4577
+ for (const directory of missingParents) {
4578
+ await guard("mkdir", directory);
4579
+ await fs2.mkdir(directory, { mode: 448 });
4580
+ await capture();
4581
+ }
4582
+ let staged;
4583
+ if (desired) {
4584
+ staged = path2.join(path2.dirname(destination), `.ntn-sync-${randomUUID2()}.pending`);
4585
+ await guard("replace", destination);
4586
+ await fs2.copyFile(path2.join(scratch, String(fileIndex)), staged, fs2.constants.COPYFILE_EXCL);
4587
+ retained.push({ path: staged, retention_path: staged });
4588
+ await capture();
4589
+ }
4590
+ if (proof.exists) {
4591
+ const backup = path2.join(path2.dirname(destination), `.ntn-sync-${randomUUID2()}.retained`);
4592
+ await guard(desired ? "replace" : "remove", destination);
4593
+ await fs2.rename(destination, backup);
4594
+ retained.push({ path: destination, retention_path: backup });
4595
+ await capture(destination);
4596
+ if (!desired) {
4597
+ const logicalFile = path2.join(expected.logical_path, relative);
4598
+ const realParent = await resolveProof(path2.dirname(logicalFile), false);
4599
+ const linkPath = path2.join(realParent.resolved_path, path2.basename(logicalFile));
4600
+ const lastLink = proof.nodes.findLast((node) => node.kind === "link" && node.path === linkPath);
4601
+ if (lastLink) {
4602
+ await guard("remove", linkPath);
4603
+ await trash(linkPath);
4604
+ retiredLinks.add(linkPath);
4605
+ await capture(linkPath);
4606
+ retained.push({ path: logicalFile, retention_path: "system_trash" });
4607
+ }
4608
+ }
4609
+ }
4610
+ if (staged) {
4611
+ await guard("replace", destination);
4612
+ await fs2.rename(staged, destination);
4613
+ retained.splice(retained.findIndex((entry) => entry.path === staged), 1);
4614
+ await capture(destination);
4615
+ }
4616
+ completed.push(relative);
4617
+ }
4618
+ const inspection = await inspect(expected.logical_path, {
4619
+ trackedPaths: incoming.map((file) => file.path)
4620
+ });
4621
+ if (!equal(inspection.file_hashes, incoming.map((file) => ({
4622
+ path: file.path,
4623
+ bytes: file.bytes.length,
4624
+ sha256: digest(file.bytes)
4625
+ }))))
4626
+ throw fail("WRITE_PARTIAL", "Local readback did not match the complete intended file set.");
4627
+ for (const entry of retained) {
4628
+ if (entry.retention_path === "system_trash")
4629
+ continue;
4630
+ await trash(entry.retention_path);
4631
+ entry.retention_path = "system_trash";
4632
+ }
4633
+ return { inspection, retained };
4634
+ } catch (error) {
4635
+ const cause = safeError(error);
4636
+ throw fail(cause.code === "SYNC_TARGET_DRIFT" ? cause.code : "WRITE_PARTIAL", cause.message, {
4637
+ operation_id: operationId,
4638
+ completed,
4639
+ retained,
4640
+ cause_code: cause.code
4641
+ });
4642
+ }
4643
+ };
4644
+ return {
4645
+ inspect: (logical, inspectOptions) => attempt(() => inspect(logical, inspectOptions)),
4646
+ commit: (expected, content, tracked, operation) => Effect12.uninterruptible(attempt(() => commit(expected, content, tracked, operation))),
4647
+ withLocks: (keys, effect) => withLocalLocks(stateRoot, keys, effect)
4648
+ };
4649
+ }
4650
+ var SyncLocalLive = Layer3.sync(SyncLocal, () => makeSyncLocal());
4651
+ // packages/core/src/sync.ts
4652
+ import { Clock as Clock4, Crypto as Crypto4, Effect as Effect13, FileSystem as FileSystem5, Schema as Schema5 } from "effect";
4653
+ var FileSchema = Schema5.Struct({
4654
+ path: Schema5.String,
4655
+ bytes: Schema5.Number,
4656
+ sha256: Schema5.String
4657
+ });
4658
+ var ContentSchema = Schema5.Struct({
4659
+ name: Schema5.String,
4660
+ description: Schema5.String,
4661
+ main: Schema5.String,
4662
+ files: Schema5.Array(FileSchema),
4663
+ content_id: Schema5.String
4664
+ });
4665
+ var BindingSchema = Schema5.Struct({
4666
+ id: Schema5.String,
4667
+ label: Schema5.String,
4668
+ page_id: Schema5.String,
4669
+ database_id: Schema5.String,
4670
+ data_source_id: Schema5.String,
4671
+ scope: Schema5.String,
4672
+ logical_path: Schema5.String,
4673
+ active: Schema5.Boolean,
4674
+ revision: Schema5.Number
4675
+ });
4676
+ var BaseSchema = Schema5.Struct({
4677
+ format: Schema5.Literal("ntn-skills-sync-base"),
4678
+ version: Schema5.Literal(1),
4679
+ binding_id: Schema5.String,
4680
+ generation: Schema5.Number,
4681
+ initialized: Schema5.Boolean,
4682
+ content: Schema5.optional(ContentSchema),
4683
+ mode: Schema5.optional(Schema5.Literals(["exact", "page_only"])),
4684
+ snapshot_id: Schema5.optional(Schema5.String),
4685
+ remote_version: Schema5.optional(Schema5.String)
4686
+ });
4687
+ var LocalSchema = Schema5.Struct({
4688
+ logical_path: Schema5.String,
4689
+ resolved_path: Schema5.String,
4690
+ exists: Schema5.Boolean,
4691
+ proof: Schema5.Unknown,
4692
+ file_hashes: Schema5.Array(FileSchema),
4693
+ content: Schema5.optional(ContentSchema)
4694
+ });
4695
+ var EdgeSchema = Schema5.Struct({
4696
+ binding: BindingSchema,
4697
+ base: BaseSchema,
4698
+ local: LocalSchema,
4699
+ remote: SnapshotSchema,
4700
+ remote_content: ContentSchema,
4701
+ mode: Schema5.Literals(["exact", "page_only"]),
4702
+ direction: Schema5.Literals(["push", "pull", "unchanged", "advance_baseline"]),
4703
+ source: Schema5.optional(Schema5.Literals(["local", "notion"])),
4704
+ intended: ContentSchema,
4705
+ actions: Schema5.Array(Schema5.Struct({
4706
+ path: Schema5.String,
4707
+ action: Schema5.Literals(["add", "update", "remove", "retain"])
4708
+ }))
4709
+ });
4710
+ var ConflictSchema = Schema5.Struct({
4711
+ code: Schema5.String,
4712
+ binding_ids: Schema5.Array(Schema5.String)
4713
+ });
4714
+ var PlanBodySchema = Schema5.Struct({
4715
+ format: Schema5.Literal("ntn-skills-sync-plan"),
4716
+ version: Schema5.Literal(1),
4717
+ applicable: Schema5.Boolean,
4718
+ bindings: Schema5.Array(EdgeSchema),
4719
+ conflicts: Schema5.Array(ConflictSchema)
4720
+ });
4721
+ var PlanSchema = Schema5.Struct({
4722
+ ...PlanBodySchema.fields,
4723
+ plan_id: Schema5.String
4724
+ });
4725
+ var ReceiptSchema = Schema5.Struct({
4726
+ format: Schema5.Literal("ntn-skills-sync-receipt"),
4727
+ version: Schema5.Literal(1),
4728
+ operation_id: Schema5.String,
4729
+ plan_id: Schema5.String,
4730
+ created_at: Schema5.Number,
4731
+ status: Schema5.Literals(["pending", "complete", "diverged"]),
4732
+ groups: Schema5.Array(Schema5.Struct({
4733
+ page_id: Schema5.String,
4734
+ stage: Schema5.Literals(["prepared", "writing", "verified"]),
4735
+ snapshot_id: Schema5.optional(Schema5.String)
4736
+ })),
4737
+ bindings: Schema5.Array(Schema5.Struct({
4738
+ binding_id: Schema5.String,
4739
+ page_id: Schema5.String,
4740
+ resolved_path: Schema5.String,
4741
+ stage: Schema5.Literals(["prepared", "writing", "verified", "complete", "diverged"]),
4742
+ generation_before: Schema5.Number,
4743
+ generation_after: Schema5.optional(Schema5.Number),
4744
+ retained: Schema5.Array(Schema5.Struct({ path: Schema5.String, retention_path: Schema5.optional(Schema5.String) }))
4745
+ })),
4746
+ failure: Schema5.optional(Schema5.Struct({ code: Schema5.String }))
4747
+ });
4748
+ var baseKey = (id) => `sync/bases/${id}.json`;
4749
+ var planKey = (id) => `sync/plans/${id}.json`;
4750
+ var receiptKey = (id) => `sync/receipts/${id}.json`;
4751
+ function stableSyncJson(value) {
4752
+ if (typeof value === "number" && !Number.isFinite(value))
4753
+ throw fail("STATE_CORRUPT", "Sync state contains a nonfinite number.");
4754
+ if (value === null || typeof value !== "object")
4755
+ return JSON.stringify(value) ?? "undefined";
4756
+ if (Array.isArray(value))
4757
+ return `[${value.map(stableSyncJson).join(",")}]`;
4758
+ const row = value;
4759
+ return `{${Object.keys(row).filter((key) => row[key] !== undefined).sort().map((key) => `${JSON.stringify(key)}:${stableSyncJson(row[key])}`).join(",")}}`;
4760
+ }
4761
+ var same = (a, b) => stableSyncJson(a) === stableSyncJson(b);
4762
+ var attempt2 = (fn) => Effect13.try({
4763
+ try: fn,
4764
+ catch: (error) => error instanceof SkillsError ? error : fail("STATE_CORRUPT", "Invalid synchronization state.")
4765
+ });
4766
+ var identity = (skill, mode) => mode === "page_only" ? referenceContentIdentity(skill) : portableIdentity(skill);
4767
+ function storageMode(snapshot) {
4768
+ return Effect13.gen(function* () {
4769
+ const api = yield* Notion;
4770
+ const raw = yield* api.request(`v1/pages/${snapshot.skill.id}`);
4771
+ const props = property(property(raw).properties);
4772
+ const values = Object.values(props).map(property);
4773
+ const files = values.some((p) => p.id === "notion%3A%2F%2Fskills%2Ffiles_property") || Boolean(property(props.Files).id);
4774
+ const references = values.some((p) => p.id === "notion%3A%2F%2Fskills%2Freferences_property") || Boolean(property(props.References).id);
4775
+ return references && !files ? "page_only" : "exact";
4776
+ });
4777
+ }
4778
+ function saveContent(skill, mode) {
4779
+ return Effect13.gen(function* () {
4780
+ yield* attempt2(() => portableFiles(skill));
4781
+ const store = yield* Store;
4782
+ const files = [];
4783
+ for (const file of [...skill.files].sort((a, b) => a.path.localeCompare(b.path))) {
4784
+ const hash = yield* sha256(file.bytes);
4785
+ yield* store.writeBytes(`objects/${hash}`, file.bytes);
4786
+ files.push({ path: file.path, bytes: file.bytes.length, sha256: hash });
4787
+ }
4788
+ return {
4789
+ name: skill.name,
4790
+ description: skill.description,
4791
+ main: skill.main,
4792
+ files,
4793
+ content_id: yield* identity(skill, mode)
4794
+ };
4795
+ });
4796
+ }
4797
+ function loadContent(content, mode) {
4798
+ return Effect13.gen(function* () {
4799
+ const store = yield* Store;
4800
+ const files = [];
4801
+ for (const file of content.files) {
4802
+ const bytes = yield* store.readBytes(`objects/${file.sha256}`);
4803
+ if (bytes.length !== file.bytes || (yield* sha256(bytes)) !== file.sha256)
4804
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "Sync content failed checksum validation.", { path: file.path }));
4805
+ files.push({ path: file.path, bytes });
4806
+ }
4807
+ const skill = {
4808
+ name: content.name,
4809
+ description: content.description,
4810
+ main: content.main,
4811
+ files
4812
+ };
4813
+ yield* attempt2(() => portableFiles(skill));
4814
+ if ((yield* identity(skill, mode)) !== content.content_id)
4815
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "Sync content identity is invalid."));
4816
+ return skill;
4817
+ });
4818
+ }
4819
+ function readBase(binding) {
4820
+ return Effect13.gen(function* () {
4821
+ const store = yield* Store;
4822
+ const base = yield* store.readJson(baseKey(binding.id), BaseSchema);
4823
+ if (!base || base.binding_id !== binding.id || !Number.isSafeInteger(base.generation) || base.generation < 0 || (base.initialized ? !base.content || !base.mode || !base.snapshot_id || !base.remote_version || base.generation < 1 : Boolean(base.content) || base.generation !== 0))
4824
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "The registered binding has missing or malformed baseline state.", {
4825
+ binding_id: binding.id
4826
+ }));
4827
+ if (base.content)
4828
+ yield* loadContent(base.content, base.mode);
4829
+ return base;
4830
+ });
4831
+ }
4832
+ function bindings(selector, all = false) {
4833
+ return Effect13.gen(function* () {
4834
+ const config = yield* configuration;
4835
+ const active = (config.sync_bindings ?? []).filter((binding) => binding.active);
4836
+ if (all)
4837
+ return active;
4838
+ const matches = active.filter((binding) => binding.id === selector || binding.label === selector);
4839
+ if (!matches.length)
4840
+ return yield* Effect13.fail(fail("SYNC_BINDING_MISSING", "No active sync binding matched.", { binding: selector }));
4841
+ if (matches.length > 1)
4842
+ return yield* Effect13.fail(fail("SYNC_BINDING_AMBIGUOUS", "Use an unambiguous binding ID.", { binding: selector }));
4843
+ return matches;
4844
+ });
4845
+ }
4846
+ function pendingReceipts() {
4847
+ return Effect13.gen(function* () {
4848
+ const store = yield* Store;
4849
+ const keys = yield* store.listKeys("sync/receipts/");
4850
+ const result = [];
4851
+ for (const key of keys) {
4852
+ const match = /^sync\/receipts\/(o_[a-f0-9-]{36})\.json$/.exec(key);
4853
+ if (!match)
4854
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "The sync receipt filename is malformed.", { key }));
4855
+ const receipt = yield* store.readJson(key, ReceiptSchema);
4856
+ if (!receipt || receipt.operation_id !== match[1])
4857
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "A sync receipt is missing or malformed.", { key }));
4858
+ const plan = yield* readPlan(receipt.plan_id);
4859
+ if (!Number.isSafeInteger(receipt.created_at) || receipt.created_at < 0 || receipt.bindings.length !== plan.bindings.length || new Set(receipt.bindings.map((entry) => entry.binding_id)).size !== receipt.bindings.length || receipt.groups.length !== new Set(plan.bindings.map((edge) => edge.binding.page_id)).size || new Set(receipt.groups.map((group) => group.page_id)).size !== receipt.groups.length)
4860
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "The retained receipt participant set is inconsistent.", { key }));
4861
+ for (const entry of receipt.bindings) {
4862
+ const edge = plan.bindings.find((item) => item.binding.id === entry.binding_id);
4863
+ if (!edge || entry.page_id !== edge.binding.page_id || entry.resolved_path !== edge.local.resolved_path || entry.generation_before !== edge.base.generation || entry.generation_after !== undefined && entry.generation_after !== edge.base.generation && entry.generation_after !== edge.base.generation + 1 || entry.stage === "complete" && entry.generation_after === undefined || receipt.status === "complete" && entry.stage !== "complete")
4864
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "The retained receipt binding state is inconsistent.", { key }));
4865
+ }
4866
+ if (receipt.groups.some((group) => !plan.bindings.some((edge) => edge.binding.page_id === group.page_id)) || receipt.status === "diverged" && !receipt.bindings.some((entry) => entry.stage === "diverged"))
4867
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "The retained receipt group state is inconsistent.", { key }));
4868
+ if (receipt.status === "pending")
4869
+ result.push(receipt);
4870
+ }
4871
+ return result;
4872
+ });
4873
+ }
4874
+ function assertUnfenced(edges) {
4875
+ return Effect13.gen(function* () {
4876
+ for (const receipt of yield* pendingReceipts()) {
4877
+ if (receipt.bindings.some((pending) => edges.some((edge) => edge.binding.page_id === pending.page_id || edge.local.resolved_path === pending.resolved_path)))
4878
+ return yield* Effect13.fail(fail("SYNC_PENDING", "Reconcile the unfinished operation before applying another plan.", {
4879
+ operation_id: receipt.operation_id,
4880
+ receipt_path: receiptKey(receipt.operation_id)
4881
+ }));
4882
+ }
4883
+ });
4884
+ }
4885
+ function verifyRemote(binding, snapshot) {
4886
+ if (snapshot.scope !== binding.scope || pageId(snapshot.skill.id) !== binding.page_id || snapshot.skill.database_id !== binding.database_id || snapshot.skill.data_source_id !== binding.data_source_id)
4887
+ return Effect13.fail(fail("SYNC_PLAN_STALE", "Bound remote identity or credential scope changed.", {
4888
+ binding_id: binding.id
4889
+ }));
4890
+ return Effect13.void;
4891
+ }
4892
+ function observe(binding, base) {
4893
+ return Effect13.gen(function* () {
4894
+ const local = yield* SyncLocal;
4895
+ const inspection = yield* local.inspect(binding.logical_path, {
4896
+ allowMissing: !base.initialized,
4897
+ ...base.content ? { trackedPaths: base.content.files.map((file) => file.path) } : {}
4898
+ });
4899
+ if (base.initialized && !inspection.exists)
4900
+ return yield* Effect13.fail(fail("SYNC_LOCAL_MISSING", "An established local Skill directory is missing.", {
4901
+ binding_id: binding.id
4902
+ }));
4903
+ const remote = yield* openSkill(binding.page_id);
4904
+ yield* verifyRemote(binding, remote);
4905
+ const mode = yield* storageMode(remote);
4906
+ if (base.initialized && base.mode !== mode)
4907
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "The bound page storage mode changed.", { binding_id: binding.id }));
4908
+ const remoteContent = yield* saveContent(yield* snapshotPortable(remote), mode);
4909
+ const localContent = inspection.content ? yield* saveContent(inspection.content, mode) : undefined;
4910
+ return { inspection, remote, mode, remoteContent, localContent };
4911
+ });
4912
+ }
4913
+ function publishConvergence(binding, expected, local, remote, mode, intendedId) {
4914
+ return Effect13.gen(function* () {
4915
+ const current = yield* readBase(binding);
4916
+ if (!same(current, expected))
4917
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "The common baseline changed.", { binding_id: binding.id }));
4918
+ yield* verifyRemote(binding, remote);
4919
+ if (!local.content || (yield* identity(local.content, mode)) !== intendedId)
4920
+ return yield* Effect13.fail(fail("SYNC_DIVERGED", "Local readback differs from the intended result.", {
4921
+ binding_id: binding.id
4922
+ }));
4923
+ const remoteContent = yield* saveContent(yield* snapshotPortable(remote), mode);
4924
+ if (remoteContent.content_id !== intendedId)
4925
+ return yield* Effect13.fail(fail("SYNC_DIVERGED", "Remote readback differs from the intended result.", {
4926
+ binding_id: binding.id
4927
+ }));
4928
+ const filesystem = yield* SyncLocal;
4929
+ const finalLocal = yield* filesystem.inspect(binding.logical_path, {
4930
+ trackedPaths: [
4931
+ ...new Set([
4932
+ ...local.file_hashes.map((file) => file.path),
4933
+ ...expected.content?.files.map((file) => file.path) ?? []
4934
+ ])
4935
+ ]
4936
+ });
4937
+ const plannedFileProofs = new Map(local.proof.files.map((file) => [file.path, file.proof]));
4938
+ for (const file of finalLocal.proof.files) {
4939
+ const before = plannedFileProofs.get(file.path);
4940
+ if (before && !same(before, file.proof))
4941
+ return yield* Effect13.fail(fail("SYNC_TARGET_DRIFT", "A final local file link or destination changed before baseline publication.", { binding_id: binding.id, path: file.path }));
4942
+ }
4943
+ if (!same(finalLocal.proof.root, local.proof.root) || !same(finalLocal.file_hashes, local.file_hashes) || !finalLocal.content || (yield* identity(finalLocal.content, mode)) !== intendedId)
4944
+ return yield* Effect13.fail(fail("SYNC_TARGET_DRIFT", "The local destination changed before common baseline publication.", { binding_id: binding.id }));
4945
+ if (expected.initialized && expected.content.content_id === intendedId)
4946
+ return expected;
4947
+ const next = {
4948
+ format: "ntn-skills-sync-base",
4949
+ version: 1,
4950
+ binding_id: binding.id,
4951
+ generation: expected.generation + 1,
4952
+ initialized: true,
4953
+ content: remoteContent,
4954
+ mode,
4955
+ snapshot_id: remote.snapshot_id,
4956
+ remote_version: remote.version_id
4957
+ };
4958
+ const store = yield* Store;
4959
+ yield* store.writeJson(baseKey(binding.id), next);
4960
+ return next;
4961
+ });
4962
+ }
4963
+ function bindSync(target, options) {
4964
+ return Effect13.gen(function* () {
4965
+ const parsed = yield* attempt2(() => parseTarget(target));
4966
+ if (parsed.snapshot || parsed.path || !options.path?.trim() || options.as !== undefined && !options.as.trim())
4967
+ return yield* Effect13.fail(fail("INVALID_ARGUMENT", "Bind requires a current pathless target, a local directory and a nonempty label."));
4968
+ const local = yield* SyncLocal;
4969
+ return yield* local.withLocks(["sync:configuration"], Effect13.gen(function* () {
4970
+ const remote = yield* openSkill(parsed.selector, { database: options.database });
4971
+ const canonical = pageId(remote.skill.id);
4972
+ if (!canonical)
4973
+ return yield* Effect13.fail(fail("INVALID_RESPONSE", "The remote page ID is invalid."));
4974
+ const inspection = yield* local.inspect(options.path, { allowMissing: true });
4975
+ const config = yield* configuration;
4976
+ const existing = config.sync_bindings ?? [];
4977
+ const duplicate = existing.find((binding) => binding.active && binding.page_id === canonical && binding.scope === remote.scope && binding.logical_path === inspection.logical_path);
4978
+ if (duplicate) {
4979
+ if (options.as !== undefined && options.as.trim() !== duplicate.label)
4980
+ return yield* Effect13.fail(fail("SYNC_BINDING_CONFLICT", "This edge is already registered with another label.", {
4981
+ binding_id: duplicate.id,
4982
+ supplied_label: options.as.trim(),
4983
+ registered_label: duplicate.label
4984
+ }));
4985
+ const base = yield* readBase(duplicate);
4986
+ if (base.initialized && !inspection.exists)
4987
+ return yield* Effect13.fail(fail("SYNC_LOCAL_MISSING", "The registered local Skill directory is missing."));
4988
+ return {
4989
+ binding: duplicate,
4990
+ logical_path: inspection.logical_path,
4991
+ resolved_path: inspection.resolved_path,
4992
+ baseline_initialized: base.initialized,
4993
+ status: base.initialized ? "initialized" : "needs_initialization",
4994
+ reused: true,
4995
+ dry_run: Boolean(options.dryRun)
4996
+ };
4997
+ }
4998
+ const label = options.as?.trim() ?? remote.skill.alias;
4999
+ if (existing.some((binding) => binding.active && binding.label === label))
5000
+ return yield* Effect13.fail(fail("SYNC_BINDING_CONFLICT", "The binding label is already in use; provide --as.", {
5001
+ label
5002
+ }));
5003
+ for (const other of existing.filter((binding) => binding.active)) {
5004
+ const otherBase = yield* readBase(other);
5005
+ const otherLocal = yield* local.inspect(other.logical_path, {
5006
+ allowMissing: !otherBase.initialized,
5007
+ ...otherBase.content ? { trackedPaths: otherBase.content.files.map((file) => file.path) } : {}
5008
+ });
5009
+ if (otherLocal.resolved_path === inspection.resolved_path && (other.page_id !== canonical || other.scope !== remote.scope))
5010
+ return yield* Effect13.fail(fail("SYNC_TARGET_CONFLICT", "The real local directory is bound to another remote page.", { binding_id: other.id }));
5011
+ }
5012
+ const id = `b_${yield* sha256(stableSyncJson([remote.scope, canonical, inspection.logical_path, label]))}`;
5013
+ const binding = {
5014
+ id,
5015
+ label,
5016
+ page_id: canonical,
5017
+ database_id: remote.skill.database_id,
5018
+ data_source_id: remote.skill.data_source_id,
5019
+ scope: remote.scope,
5020
+ logical_path: inspection.logical_path,
5021
+ active: true,
5022
+ revision: (existing.find((item) => item.id === id)?.revision ?? 0) + 1
5023
+ };
5024
+ const mode = yield* storageMode(remote);
5025
+ const remoteContent = yield* saveContent(yield* snapshotPortable(remote), mode);
5026
+ const equal = inspection.content !== undefined && (yield* identity(inspection.content, mode)) === remoteContent.content_id;
5027
+ const preservedBase = existing.find((item) => item.id === id);
5028
+ const initialized = equal || (preservedBase ? (yield* readBase(preservedBase)).initialized : false);
5029
+ if (!options.dryRun) {
5030
+ const store = yield* Store;
5031
+ const prior = existing.find((item) => item.id === id);
5032
+ if (!prior && (yield* store.readJson(baseKey(id), BaseSchema)) !== undefined)
5033
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "A retained orphan baseline exists for this registration; it cannot be overwritten.", { binding_id: id, baseline_path: `${store.root}/${baseKey(id)}` }));
5034
+ const base = prior ? yield* readBase(prior) : {
5035
+ format: "ntn-skills-sync-base",
5036
+ version: 1,
5037
+ binding_id: id,
5038
+ generation: 0,
5039
+ initialized: false,
5040
+ mode
5041
+ };
5042
+ if (!prior)
5043
+ yield* store.writeJson(baseKey(id), base);
5044
+ if (equal) {
5045
+ const checkedRemote = yield* openSkill(canonical);
5046
+ if (checkedRemote.version_id !== remote.version_id)
5047
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "The remote changed during registration."));
5048
+ const checkedLocal = yield* local.inspect(inspection.logical_path, {
5049
+ allowMissing: true
5050
+ });
5051
+ if (!same(checkedLocal.proof, inspection.proof) || !same(checkedLocal.file_hashes, inspection.file_hashes))
5052
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "The local target changed during registration."));
5053
+ yield* publishConvergence(binding, base, checkedLocal, checkedRemote, mode, remoteContent.content_id);
5054
+ }
5055
+ yield* store.writeJson("config.json", {
5056
+ ...config,
5057
+ sync_bindings: [...existing.filter((item) => item.id !== id), binding]
5058
+ });
5059
+ }
5060
+ return {
5061
+ binding,
5062
+ logical_path: inspection.logical_path,
5063
+ resolved_path: inspection.resolved_path,
5064
+ baseline_initialized: initialized,
5065
+ status: initialized ? "initialized" : "needs_initialization",
5066
+ dry_run: Boolean(options.dryRun),
5067
+ reused: false
5068
+ };
5069
+ }));
5070
+ });
5071
+ }
5072
+ function classify(base, localId, remoteId, from) {
5073
+ if (from === "local")
5074
+ return localId === undefined ? "conflict" : localId === remoteId ? base.content?.content_id === localId ? "unchanged" : "advance_baseline" : "push";
5075
+ if (from === "notion")
5076
+ return localId === remoteId ? base.content?.content_id === remoteId ? "unchanged" : "advance_baseline" : "pull";
5077
+ if (!base.initialized)
5078
+ return "conflict";
5079
+ if (localId === remoteId)
5080
+ return localId === base.content.content_id ? "unchanged" : "advance_baseline";
5081
+ if (localId === base.content.content_id)
5082
+ return "pull";
5083
+ if (remoteId === base.content.content_id)
5084
+ return "push";
5085
+ return "conflict";
5086
+ }
5087
+ function fileActions(local, intended) {
5088
+ const current = new Map((local?.files ?? []).map((file) => [file.path, file.sha256]));
5089
+ const desired = new Map(intended.files.map((file) => [file.path, file.sha256]));
5090
+ return [...new Set([...current.keys(), ...desired.keys()])].sort().map((path) => ({
5091
+ path,
5092
+ action: !desired.has(path) ? "remove" : !current.has(path) ? "add" : current.get(path) === desired.get(path) ? "retain" : "update"
5093
+ }));
5094
+ }
5095
+ function planSync(binding, options = {}) {
5096
+ return Effect13.gen(function* () {
5097
+ if (Boolean(binding) === Boolean(options.all) || options.all && options.from || options.from !== undefined && options.from !== "local" && options.from !== "notion")
5098
+ return yield* Effect13.fail(fail("INVALID_ARGUMENT", "Choose exactly one binding or --all; --from is single-binding only."));
5099
+ const local = yield* SyncLocal;
5100
+ return yield* local.withLocks(["sync:configuration"], Effect13.gen(function* () {
5101
+ const selected = yield* bindings(binding, Boolean(options.all));
5102
+ if (!selected.length)
5103
+ return yield* Effect13.fail(fail("SYNC_BINDING_MISSING", "No active bindings are registered."));
5104
+ const edges = [];
5105
+ const conflicts = [];
5106
+ for (const item of [...selected].sort((a, b) => a.id.localeCompare(b.id))) {
5107
+ const base = yield* readBase(item);
5108
+ const observed = yield* observe(item, base);
5109
+ const direction = classify(base, observed.localContent?.content_id, observed.remoteContent.content_id, options.from);
5110
+ if (direction === "conflict")
5111
+ conflicts.push({
5112
+ code: !base.initialized ? "SYNC_INITIALIZATION_REQUIRED" : "SYNC_CONFLICT",
5113
+ binding_ids: [item.id]
5114
+ });
5115
+ const intended = direction === "push" ? observed.localContent : observed.remoteContent;
5116
+ edges.push({
5117
+ binding: item,
5118
+ base,
5119
+ local: {
5120
+ logical_path: observed.inspection.logical_path,
5121
+ resolved_path: observed.inspection.resolved_path,
5122
+ exists: observed.inspection.exists,
5123
+ proof: observed.inspection.proof,
5124
+ file_hashes: observed.inspection.file_hashes,
5125
+ ...observed.localContent ? { content: observed.localContent } : {}
5126
+ },
5127
+ remote: observed.remote,
5128
+ remote_content: observed.remoteContent,
5129
+ mode: observed.mode,
5130
+ direction: direction === "conflict" ? "unchanged" : direction,
5131
+ ...options.from ? { source: options.from } : {},
5132
+ intended,
5133
+ actions: fileActions(observed.localContent, intended)
5134
+ });
5135
+ }
5136
+ const pages = new Map;
5137
+ const targets = new Map;
5138
+ for (const edge of edges) {
5139
+ pages.set(edge.binding.page_id, [...pages.get(edge.binding.page_id) ?? [], edge]);
5140
+ targets.set(edge.local.resolved_path, [
5141
+ ...targets.get(edge.local.resolved_path) ?? [],
5142
+ edge
5143
+ ]);
5144
+ }
5145
+ for (const group of targets.values())
5146
+ if (new Set(group.map((edge) => `${edge.binding.scope}:${edge.binding.page_id}`)).size > 1)
5147
+ conflicts.push({
5148
+ code: "SYNC_TARGET_CONFLICT",
5149
+ binding_ids: group.map((edge) => edge.binding.id)
5150
+ });
5151
+ for (const group of pages.values()) {
5152
+ if (new Set(group.map((edge) => `${edge.binding.scope}:${edge.remote.version_id}:${edge.mode}`)).size > 1)
5153
+ conflicts.push({
5154
+ code: "SYNC_PLAN_STALE",
5155
+ binding_ids: group.map((edge) => edge.binding.id)
5156
+ });
5157
+ const pushes = group.filter((edge) => edge.direction === "push");
5158
+ if (new Set(pushes.map((edge) => edge.intended.content_id)).size > 1) {
5159
+ conflicts.push({
5160
+ code: "SYNC_CONFLICT",
5161
+ binding_ids: pushes.map((edge) => edge.binding.id)
5162
+ });
5163
+ continue;
5164
+ }
5165
+ if (pushes.length) {
5166
+ const accepted = pushes[0].intended;
5167
+ for (const edge of group) {
5168
+ if (edge.direction !== "push") {
5169
+ if (edge.local.content && edge.local.content.content_id !== edge.base.content?.content_id && edge.local.content.content_id !== accepted.content_id) {
5170
+ conflicts.push({
5171
+ code: "SYNC_CONFLICT",
5172
+ binding_ids: [edge.binding.id, pushes[0].binding.id]
5173
+ });
5174
+ continue;
5175
+ }
5176
+ edge.intended = accepted;
5177
+ edge.direction = edge.local.content?.content_id === accepted.content_id ? "advance_baseline" : "pull";
5178
+ edge.actions = fileActions(edge.local.content, accepted);
5179
+ }
5180
+ }
5181
+ }
5182
+ }
5183
+ const body = yield* attempt2(() => Schema5.decodeUnknownSync(PlanBodySchema)({
5184
+ format: "ntn-skills-sync-plan",
5185
+ version: 1,
5186
+ applicable: !conflicts.length,
5187
+ bindings: edges,
5188
+ conflicts
5189
+ }));
5190
+ const id = `p_${yield* sha256(stableSyncJson(body))}`;
5191
+ const plan = { ...body, plan_id: id };
5192
+ const store = yield* Store;
5193
+ yield* store.writeJson(planKey(id), plan);
5194
+ const bytes = new TextEncoder().encode(stableSyncJson(plan) + `
5195
+ `);
5196
+ const copy = options.output ? yield* store.output(options.output, bytes) : undefined;
5197
+ const result = {
5198
+ ...plan,
5199
+ plan_path: `${store.root}/${planKey(id)}`,
5200
+ ...copy ? { output: copy.output, reused: copy.reused } : {}
5201
+ };
5202
+ if (conflicts.length)
5203
+ return yield* Effect13.fail(fail(conflicts[0].code, "The saved sync plan contains conflicts and cannot be applied.", result));
5204
+ return result;
5205
+ }));
5206
+ });
5207
+ }
5208
+ function readPlan(input) {
5209
+ return Effect13.gen(function* () {
5210
+ const store = yield* Store;
5211
+ let plan;
5212
+ if (/^p_[a-f0-9]{64}$/.test(input))
5213
+ plan = yield* store.readJson(planKey(input), PlanSchema);
5214
+ else {
5215
+ const fs = yield* FileSystem5.FileSystem;
5216
+ const raw = yield* fs.readFileString(input).pipe(Effect13.mapError(() => fail("SYNC_PLAN_MISSING", "Could not read the saved plan file.")));
5217
+ plan = yield* attempt2(() => {
5218
+ const rawPlan = JSON.parse(raw);
5219
+ const decoded = Schema5.decodeUnknownSync(PlanSchema)(rawPlan);
5220
+ if (!same(rawPlan, decoded))
5221
+ throw fail("STATE_CORRUPT", "Plan copies cannot add undocumented fields.");
5222
+ return decoded;
5223
+ });
5224
+ }
5225
+ if (!plan)
5226
+ return yield* Effect13.fail(fail("SYNC_PLAN_MISSING", "The saved sync plan is missing."));
5227
+ const { plan_id, ...body } = plan;
5228
+ if (!/^p_[a-f0-9]{64}$/.test(plan_id) || `p_${yield* sha256(stableSyncJson(body))}` !== plan_id || /^p_[a-f0-9]{64}$/.test(input) && input !== plan_id)
5229
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "The saved sync plan digest is invalid."));
5230
+ if (!plan.applicable || plan.conflicts.length || !plan.bindings.length)
5231
+ return yield* Effect13.fail(fail("SYNC_CONFLICT", "This saved plan is not executable.", { plan_id }));
5232
+ if (new Set(plan.bindings.map((edge) => edge.binding.id)).size !== plan.bindings.length)
5233
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "The saved plan contains duplicate binding IDs."));
5234
+ const registered = yield* store.readJson(planKey(plan_id), PlanSchema);
5235
+ if (!registered || !same(registered, plan))
5236
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "A copied plan must exactly match its registered immutable artifact.", { plan_id }));
5237
+ const groupResults = new Map;
5238
+ for (const edge of plan.bindings) {
5239
+ const candidate = groupResults.get(edge.binding.page_id);
5240
+ if (candidate !== undefined && candidate !== edge.intended.content_id)
5241
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "A saved page group has incompatible intended results."));
5242
+ groupResults.set(edge.binding.page_id, edge.intended.content_id);
5243
+ }
5244
+ for (const edge of plan.bindings) {
5245
+ yield* loadContent(edge.intended, edge.mode);
5246
+ yield* loadContent(edge.remote_content, edge.mode);
5247
+ if (edge.local.content)
5248
+ yield* loadContent(edge.local.content, edge.mode);
5249
+ if (!same(edge.actions, fileActions(edge.local.content, edge.intended)))
5250
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "Saved plan file actions are invalid."));
5251
+ if (edge.base.binding_id !== edge.binding.id || edge.local.logical_path !== edge.binding.logical_path || edge.remote.scope !== edge.binding.scope || pageId(edge.remote.skill.id) !== edge.binding.page_id || edge.remote.skill.database_id !== edge.binding.database_id || edge.remote.skill.data_source_id !== edge.binding.data_source_id)
5252
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "Saved plan participant identities are inconsistent."));
5253
+ }
5254
+ return plan;
5255
+ });
5256
+ }
5257
+ function preflight(plan) {
5258
+ return Effect13.gen(function* () {
5259
+ const selected = yield* bindings(undefined, true);
5260
+ const observed = new Map;
5261
+ for (const edge of plan.bindings) {
5262
+ const binding = selected.find((item) => item.id === edge.binding.id);
5263
+ if (!binding || !same(binding, edge.binding))
5264
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "The binding configuration changed.", {
5265
+ binding_id: edge.binding.id
5266
+ }));
5267
+ const base = yield* readBase(binding);
5268
+ if (!same(base, edge.base))
5269
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "The common baseline changed.", { binding_id: binding.id }));
5270
+ const current = yield* observe(binding, base);
5271
+ if (current.mode !== edge.mode || current.remote.snapshot_id !== edge.remote.snapshot_id || current.remote.version_id !== edge.remote.version_id || current.remoteContent.content_id !== edge.remote_content.content_id || current.inspection.exists !== edge.local.exists || current.inspection.logical_path !== edge.local.logical_path || current.inspection.resolved_path !== edge.local.resolved_path || !same(current.inspection.proof, edge.local.proof) || !same(current.inspection.file_hashes, edge.local.file_hashes) || !same(current.localContent, edge.local.content))
5272
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "Remote content, local content or the filesystem target changed.", { binding_id: binding.id }));
5273
+ for (const other of selected) {
5274
+ if (other.id === binding.id)
5275
+ continue;
5276
+ const otherBase = yield* readBase(other);
5277
+ const local = yield* SyncLocal;
5278
+ const target = yield* local.inspect(other.logical_path, {
5279
+ allowMissing: !otherBase.initialized,
5280
+ ...otherBase.content ? { trackedPaths: otherBase.content.files.map((file) => file.path) } : {}
5281
+ });
5282
+ if (target.resolved_path === current.inspection.resolved_path && (other.page_id !== binding.page_id || other.scope !== binding.scope))
5283
+ return yield* Effect13.fail(fail("SYNC_TARGET_CONFLICT", "An active binding targets this real directory from another page."));
5284
+ }
5285
+ observed.set(binding.id, current);
5286
+ }
5287
+ yield* assertUnfenced(plan.bindings);
5288
+ return observed;
5289
+ });
5290
+ }
5291
+ function applySync(planIdOrFile) {
5292
+ return Effect13.gen(function* () {
5293
+ const plan = yield* readPlan(planIdOrFile);
5294
+ const local = yield* SyncLocal;
5295
+ return yield* local.withLocks([
5296
+ "sync:configuration",
5297
+ ...plan.bindings.flatMap((edge) => [
5298
+ `sync:page:${edge.binding.page_id}`,
5299
+ `sync:target:${edge.local.resolved_path}`
5300
+ ])
5301
+ ], Effect13.gen(function* () {
5302
+ const initial = yield* preflight(plan);
5303
+ const store = yield* Store;
5304
+ const crypto = yield* Crypto4.Crypto;
5305
+ const operationId = `o_${yield* crypto.randomUUIDv4()}`;
5306
+ const groups = [...new Set(plan.bindings.map((edge) => edge.binding.page_id))].map((page_id) => ({ page_id, stage: "prepared" }));
5307
+ const receipt = {
5308
+ format: "ntn-skills-sync-receipt",
5309
+ version: 1,
5310
+ operation_id: operationId,
5311
+ plan_id: plan.plan_id,
5312
+ created_at: yield* Clock4.currentTimeMillis,
5313
+ status: "pending",
5314
+ groups,
5315
+ bindings: plan.bindings.map((edge) => ({
5316
+ binding_id: edge.binding.id,
5317
+ page_id: edge.binding.page_id,
5318
+ resolved_path: edge.local.resolved_path,
5319
+ stage: "prepared",
5320
+ generation_before: edge.base.generation,
5321
+ retained: []
5322
+ }))
5323
+ };
5324
+ yield* store.writeJson(receiptKey(operationId), receipt);
5325
+ const save = () => store.writeJson(receiptKey(operationId), receipt);
5326
+ const execute = Effect13.gen(function* () {
5327
+ const committed = new Map;
5328
+ for (const group of receipt.groups) {
5329
+ const edges = plan.bindings.filter((edge) => edge.binding.page_id === group.page_id).sort((a, b) => Number(b.direction === "push") - Number(a.direction === "push") || a.binding.id.localeCompare(b.binding.id));
5330
+ const representative = edges[0];
5331
+ const push = edges.find((edge) => edge.direction === "push");
5332
+ let remote = initial.get(representative.binding.id).remote;
5333
+ if (push) {
5334
+ group.stage = "writing";
5335
+ yield* save();
5336
+ yield* importPortable(yield* loadContent(push.intended, push.mode), push.remote);
5337
+ }
5338
+ remote = yield* openSkill(group.page_id);
5339
+ yield* verifyRemote(representative.binding, remote);
5340
+ if ((yield* identity(yield* snapshotPortable(remote), representative.mode)) !== representative.intended.content_id)
5341
+ return yield* Effect13.fail(fail("SYNC_DIVERGED", "Remote write readback did not match the saved intended result.", { page_id: group.page_id }));
5342
+ group.stage = "verified";
5343
+ group.snapshot_id = remote.snapshot_id;
5344
+ yield* save();
5345
+ for (const edge of edges) {
5346
+ const entry = receipt.bindings.find((item) => item.binding_id === edge.binding.id);
5347
+ let inspection = initial.get(edge.binding.id).inspection;
5348
+ entry.stage = "writing";
5349
+ yield* save();
5350
+ const targetKey = `${edge.binding.page_id}:${edge.local.resolved_path}`;
5351
+ const already = committed.get(targetKey);
5352
+ if (already) {
5353
+ inspection = yield* local.inspect(edge.binding.logical_path, {
5354
+ trackedPaths: edge.intended.files.map((file) => file.path)
5355
+ });
5356
+ if (!same(inspection.proof.root, property(edge.local.proof).root))
5357
+ return yield* Effect13.fail(fail("SYNC_TARGET_DRIFT", "A duplicate real target link chain changed during apply."));
5358
+ } else if (edge.local.content?.content_id !== edge.intended.content_id) {
5359
+ const result = yield* local.commit(inspection, yield* loadContent(edge.intended, edge.mode), [
5360
+ ...new Set([
5361
+ ...edge.base.content?.files.map((file) => file.path) ?? [],
5362
+ ...edge.local.content?.files.map((file) => file.path) ?? []
5363
+ ])
5364
+ ], operationId);
5365
+ inspection = result.inspection;
5366
+ entry.retained = [...result.retained];
5367
+ committed.set(targetKey, inspection);
5368
+ } else {
5369
+ const fresh = yield* local.inspect(edge.binding.logical_path, {
5370
+ allowMissing: !edge.base.initialized,
5371
+ ...edge.base.content ? { trackedPaths: edge.base.content.files.map((file) => file.path) } : {}
5372
+ });
5373
+ if (!same(fresh.proof, inspection.proof) || !same(fresh.file_hashes, inspection.file_hashes))
5374
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "Local target changed at the commit boundary.", {
5375
+ binding_id: edge.binding.id
5376
+ }));
5377
+ inspection = fresh;
5378
+ committed.set(targetKey, inspection);
5379
+ }
5380
+ const checkedRemote = yield* openSkill(edge.binding.page_id);
5381
+ const checkedLocal = yield* local.inspect(edge.binding.logical_path, {
5382
+ trackedPaths: edge.intended.files.map((file) => file.path)
5383
+ });
5384
+ if (!same(checkedLocal.proof, inspection.proof) || !same(checkedLocal.file_hashes, inspection.file_hashes))
5385
+ return yield* Effect13.fail(fail("SYNC_TARGET_DRIFT", "Local destination changed after the commit boundary.", { binding_id: edge.binding.id }));
5386
+ entry.stage = "verified";
5387
+ yield* save();
5388
+ const next = yield* publishConvergence(edge.binding, edge.base, checkedLocal, checkedRemote, edge.mode, edge.intended.content_id);
5389
+ entry.stage = "complete";
5390
+ entry.generation_after = next.generation;
5391
+ yield* save();
5392
+ }
5393
+ }
5394
+ receipt.status = "complete";
5395
+ yield* save();
5396
+ return {
5397
+ plan_id: plan.plan_id,
5398
+ operation_id: operationId,
5399
+ verified: true,
5400
+ receipt_path: `${store.root}/${receiptKey(operationId)}`,
5401
+ receipt,
5402
+ bindings: receipt.bindings.map((entry) => {
5403
+ const edge = plan.bindings.find((item) => item.binding.id === entry.binding_id);
5404
+ const snapshotId = receipt.groups.find((group) => group.page_id === edge.binding.page_id)?.snapshot_id;
5405
+ return {
5406
+ ...entry,
5407
+ action: edge.direction,
5408
+ verified: true,
5409
+ content_id: edge.intended.content_id,
5410
+ snapshot_id: snapshotId,
5411
+ page_id: edge.binding.page_id
5412
+ };
5413
+ })
5414
+ };
5415
+ });
5416
+ return yield* execute.pipe(Effect13.catch((error) => Effect13.gen(function* () {
5417
+ receipt.status = "pending";
5418
+ receipt.failure = { code: error.code };
5419
+ yield* save();
5420
+ return yield* Effect13.fail(fail(error.code, error.message, {
5421
+ operation_id: operationId,
5422
+ receipt_path: `${store.root}/${receiptKey(operationId)}`,
5423
+ cause_details: error.details,
5424
+ receipt
5425
+ }));
5426
+ })));
5427
+ }));
5428
+ });
5429
+ }
5430
+ function syncStatus(binding, options = {}) {
5431
+ return Effect13.gen(function* () {
5432
+ const selected = yield* bindings(binding, !binding);
5433
+ const local = yield* SyncLocal;
5434
+ const pending = yield* pendingReceipts();
5435
+ const policy = yield* effectiveCachePolicy;
5436
+ const now = yield* Clock4.currentTimeMillis;
5437
+ const results = [];
5438
+ for (const item of selected) {
5439
+ const base = yield* readBase(item);
5440
+ const inspection = yield* local.inspect(item.logical_path, {
5441
+ allowMissing: !base.initialized,
5442
+ ...base.content ? { trackedPaths: base.content.files.map((file) => file.path) } : {}
5443
+ });
5444
+ const observation = options.refresh ? { snapshot: yield* openSkill(item.page_id), validated_at: now } : yield* cachedRemoteObservation(item.page_id, item.scope);
5445
+ if (observation)
5446
+ yield* verifyRemote(item, observation.snapshot);
5447
+ const mode = observation && options.refresh ? yield* storageMode(observation.snapshot) : base.mode;
5448
+ const localId = inspection.content ? yield* identity(inspection.content, mode ?? "exact") : undefined;
5449
+ const remoteId = observation ? yield* identity(yield* snapshotPortable(observation.snapshot), mode ?? "exact") : undefined;
5450
+ const age = observation ? now - observation.validated_at : undefined;
5451
+ const stale = age === undefined ? null : !Number.isFinite(age) || age < 0 || age >= policy.read_max_age_ms;
5452
+ const related = pending.filter((receipt) => receipt.bindings.some((entry) => entry.page_id === item.page_id || entry.resolved_path === inspection.resolved_path));
5453
+ results.push({
5454
+ binding: item,
5455
+ logical_path: inspection.logical_path,
5456
+ resolved_path: inspection.resolved_path,
5457
+ baseline_initialized: base.initialized,
5458
+ baseline_generation: base.generation,
5459
+ common_content_id: base.content?.content_id ?? null,
5460
+ local_content_id: localId ?? null,
5461
+ remote_content_id: remoteId ?? null,
5462
+ remote_snapshot_id: observation?.snapshot.snapshot_id ?? null,
5463
+ remote_version: observation?.snapshot.version_id ?? null,
5464
+ remote_validated_at: observation?.validated_at ?? null,
5465
+ remote_age_ms: age ?? null,
5466
+ remote_stale: stale,
5467
+ remote_freshness: !observation ? "unknown" : options.refresh ? "validated" : stale ? "stale" : "observed",
5468
+ equality_mode: mode ?? "unknown",
5469
+ authoritative: Boolean(options.refresh),
5470
+ provisional: !options.refresh,
5471
+ status: !base.initialized ? "needs_initialization" : remoteId === undefined || localId === undefined ? "unknown" : classify(base, localId, remoteId),
5472
+ pending_receipts: related.map((receipt) => ({
5473
+ operation_id: receipt.operation_id,
5474
+ receipt_path: receiptKey(receipt.operation_id)
5475
+ }))
5476
+ });
5477
+ }
5478
+ return { bindings: results };
5479
+ });
5480
+ }
5481
+ function unbindSync(binding, options = {}) {
5482
+ return Effect13.gen(function* () {
5483
+ const local = yield* SyncLocal;
5484
+ return yield* local.withLocks(["sync:configuration"], Effect13.gen(function* () {
5485
+ const selected = (yield* bindings(binding))[0];
5486
+ yield* readBase(selected);
5487
+ const next = { ...selected, active: false, revision: selected.revision + 1 };
5488
+ if (!options.dryRun) {
5489
+ const config = yield* configuration;
5490
+ const store = yield* Store;
5491
+ yield* store.writeJson("config.json", {
5492
+ ...config,
5493
+ sync_bindings: (config.sync_bindings ?? []).map((item) => item.id === selected.id ? next : item)
5494
+ });
5495
+ }
5496
+ return {
5497
+ binding: options.dryRun ? selected : next,
5498
+ dry_run: Boolean(options.dryRun),
5499
+ deactivated: !options.dryRun,
5500
+ retained: {
5501
+ local_content: true,
5502
+ remote_content: true,
5503
+ baseline: true,
5504
+ plans: true,
5505
+ receipts: true
5506
+ }
5507
+ };
5508
+ }));
5509
+ });
5510
+ }
5511
+ function reconcileSync(binding) {
5512
+ return Effect13.gen(function* () {
5513
+ const local = yield* SyncLocal;
5514
+ return yield* local.withLocks(["sync:configuration"], Effect13.gen(function* () {
5515
+ const registered = (yield* configuration).sync_bindings ?? [];
5516
+ const matches = registered.filter((item) => item.id === binding || item.label === binding);
5517
+ if (!matches.length)
5518
+ return yield* Effect13.fail(fail("SYNC_BINDING_MISSING", "No retained binding matched reconciliation."));
5519
+ if (matches.length > 1)
5520
+ return yield* Effect13.fail(fail("SYNC_BINDING_AMBIGUOUS", "Use a retained binding ID for reconciliation."));
5521
+ const selected = matches[0];
5522
+ const base = yield* readBase(selected);
5523
+ const root = yield* local.inspect(selected.logical_path, {
5524
+ allowMissing: !base.initialized,
5525
+ ...base.content ? { trackedPaths: base.content.files.map((file) => file.path) } : {}
5526
+ });
5527
+ const receipts = (yield* pendingReceipts()).filter((receipt) => receipt.bindings.some((entry) => entry.page_id === selected.page_id || entry.resolved_path === root.resolved_path));
5528
+ if (!receipts.length)
5529
+ return {
5530
+ binding: selected,
5531
+ outcome: "no_pending_operation",
5532
+ baseline_advanced: false,
5533
+ receipts: []
5534
+ };
5535
+ const store = yield* Store;
5536
+ const results = [];
5537
+ for (const receipt of receipts) {
5538
+ const plan = yield* readPlan(receipt.plan_id);
5539
+ const active = (yield* configuration).sync_bindings ?? [];
5540
+ let diverged = false;
5541
+ let advanced = false;
5542
+ for (const entry of receipt.bindings) {
5543
+ const edge = plan.bindings.find((item) => item.binding.id === entry.binding_id);
5544
+ if (!edge)
5545
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "Receipt references a binding absent from its plan."));
5546
+ const currentBinding = active.find((item) => item.id === entry.binding_id);
5547
+ const permittedDeactivation = currentBinding && !currentBinding.active && currentBinding.revision === edge.binding.revision + 1;
5548
+ if (!currentBinding || !(same(currentBinding, edge.binding) || permittedDeactivation && same({
5549
+ ...currentBinding,
5550
+ active: edge.binding.active,
5551
+ revision: edge.binding.revision
5552
+ }, edge.binding)))
5553
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "The unfinished operation binding target changed; its fence is retained.", { operation_id: receipt.operation_id }));
5554
+ const currentBase = yield* readBase(currentBinding);
5555
+ let inspection = yield* local.inspect(currentBinding.logical_path, {
5556
+ allowMissing: !currentBase.initialized,
5557
+ trackedPaths: [
5558
+ ...new Set([
5559
+ ...edge.intended.files.map((file) => file.path),
5560
+ ...edge.base.content?.files.map((file) => file.path) ?? []
5561
+ ])
5562
+ ]
5563
+ });
5564
+ if (inspection.resolved_path !== entry.resolved_path)
5565
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "The unfinished operation filesystem target changed; its fence is retained.", { operation_id: receipt.operation_id }));
5566
+ const originalProof = property(edge.local.proof);
5567
+ const originalRoot = property(originalProof.root);
5568
+ const oldNodes = Array.isArray(originalRoot.nodes) ? originalRoot.nodes : [];
5569
+ const newNodes = inspection.proof.root.nodes;
5570
+ if (!oldNodes.length || !same(oldNodes, edge.local.exists ? newNodes : newNodes.slice(0, oldNodes.length)))
5571
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "The unfinished operation link chain changed; its fence is retained.", { operation_id: receipt.operation_id }));
5572
+ const originalFiles = Array.isArray(originalProof.files) ? originalProof.files : [];
5573
+ for (const oldFile of originalFiles) {
5574
+ const oldEntry = property(oldFile);
5575
+ const oldProof = property(oldEntry.proof);
5576
+ const oldFileNodes = Array.isArray(oldProof.nodes) ? oldProof.nodes.map(property) : [];
5577
+ const nextFile = inspection.proof.files.find((file) => file.path === oldEntry.path);
5578
+ if (!nextFile) {
5579
+ if (edge.intended.files.some((file) => file.path === oldEntry.path))
5580
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "A retained intended local file destination is unavailable."));
5581
+ continue;
5582
+ }
5583
+ const immutableNodes = oldFileNodes.filter((node) => node.kind !== "file");
5584
+ if (oldProof.resolved_path !== nextFile.proof.resolved_path || !same(immutableNodes, nextFile.proof.nodes.filter((node) => node.kind !== "file")))
5585
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "A local file link or parent changed during the unfinished operation; its fence is retained.", { operation_id: receipt.operation_id, path: oldEntry.path }));
5586
+ }
5587
+ const remote = yield* openSkill(currentBinding.page_id);
5588
+ yield* verifyRemote(currentBinding, remote);
5589
+ const mode = yield* storageMode(remote);
5590
+ if (mode !== edge.mode)
5591
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "The unfinished operation storage mode changed; its fence is retained."));
5592
+ const rechecked = yield* local.inspect(currentBinding.logical_path, {
5593
+ allowMissing: !currentBase.initialized,
5594
+ trackedPaths: [
5595
+ ...new Set([
5596
+ ...edge.intended.files.map((file) => file.path),
5597
+ ...edge.base.content?.files.map((file) => file.path) ?? []
5598
+ ])
5599
+ ]
5600
+ });
5601
+ if (!same(inspection.proof, rechecked.proof) || !same(inspection.file_hashes, rechecked.file_hashes))
5602
+ return yield* Effect13.fail(fail("SYNC_TARGET_DRIFT", "The local target changed during reconciliation; its fence is retained."));
5603
+ inspection = rechecked;
5604
+ const localId = inspection.content ? yield* identity(inspection.content, mode) : undefined;
5605
+ const remoteId = yield* identity(yield* snapshotPortable(remote), mode);
5606
+ if (localId === edge.intended.content_id && remoteId === edge.intended.content_id) {
5607
+ if (!same(currentBase, edge.base) && !(currentBase.initialized && currentBase.generation === edge.base.generation + 1 && currentBase.content?.content_id === edge.intended.content_id))
5608
+ return yield* Effect13.fail(fail("SYNC_PLAN_STALE", "The unfinished operation common baseline changed."));
5609
+ if (entry.stage === "complete") {
5610
+ if (!currentBase.initialized || currentBase.content?.content_id !== edge.intended.content_id || currentBase.generation !== entry.generation_after)
5611
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "A verified receipt edge disagrees with its published common baseline."));
5612
+ continue;
5613
+ }
5614
+ const next = yield* publishConvergence(currentBinding, currentBase, inspection, remote, mode, edge.intended.content_id);
5615
+ advanced ||= next.generation > edge.base.generation;
5616
+ entry.stage = "complete";
5617
+ entry.generation_after = next.generation;
5618
+ } else {
5619
+ if (!same(currentBase, edge.base) && !(entry.stage === "complete" && currentBase.initialized && currentBase.generation === entry.generation_after && currentBase.content?.content_id === edge.intended.content_id))
5620
+ return yield* Effect13.fail(fail("STATE_CORRUPT", "A divergent unfinished operation has an unexpected common baseline."));
5621
+ entry.stage = "diverged";
5622
+ diverged = true;
5623
+ }
5624
+ yield* store.writeJson(receiptKey(receipt.operation_id), receipt);
5625
+ }
5626
+ receipt.status = diverged ? "diverged" : "complete";
5627
+ yield* store.writeJson(receiptKey(receipt.operation_id), receipt);
5628
+ results.push({
5629
+ operation_id: receipt.operation_id,
5630
+ outcome: receipt.status,
5631
+ baseline_advanced: advanced,
5632
+ receipt_path: `${store.root}/${receiptKey(receipt.operation_id)}`,
5633
+ receipt
5634
+ });
5635
+ }
5636
+ const result = {
5637
+ binding: selected,
5638
+ outcome: results.some((item) => item.outcome === "diverged") ? "diverged" : "complete",
5639
+ baseline_advanced: results.some((item) => item.baseline_advanced),
5640
+ receipts: results
5641
+ };
5642
+ if (result.outcome === "diverged")
5643
+ return yield* Effect13.fail(fail("SYNC_DIVERGED", "Fresh readback classified divergence; old common baselines are retained and no mutation was replayed.", result));
5644
+ return result;
5645
+ }));
2925
5646
  });
2926
5647
  }
2927
5648
  // packages/cli/package.json
2928
- var version = "0.1.2";
5649
+ var version = "0.2.0";
2929
5650
 
2930
5651
  // packages/cli/src/main.ts
2931
5652
  var requiredDatabaseFlag = Flag.String("database").pipe(Flag.between(1, 1), Flag.map((values) => values[0]), Flag.withDescription("One Skills Database ID, URL or exact registered alias; repeated --database is rejected"));
2932
5653
  var databaseFlag = Flag.String("database").pipe(Flag.atMost(1), Flag.map((values) => Option.fromUndefinedOr(values[0])), Flag.withDescription("Restrict to one Skills Database ID, URL or exact registered alias; repeated --database is rejected"));
2933
- var refreshFlag = Flag.Boolean("refresh").pipe(Flag.withDefault(false), Flag.withDescription("Bypass the 60-second metadata cache"));
5654
+ var singleton = (name, description) => Flag.String(name).pipe(Flag.atMost(1), Flag.map((values) => Option.fromUndefinedOr(values[0])), Flag.withDescription(description));
5655
+ var requiredSingleton = (name, description) => Flag.String(name).pipe(Flag.between(1, 1), Flag.map((values) => values[0]), Flag.withDescription(description));
5656
+ var switchFlag = (name, description) => Flag.Boolean(name).pipe(Flag.atMost(1), Flag.map((values) => values[0] ?? false), Flag.withDescription(description));
5657
+ var refreshFlag = switchFlag("refresh", "Validate online regardless of cache age");
5658
+ var readPolicyFlags = {
5659
+ refresh: refreshFlag,
5660
+ offline: switchFlag("offline", "Read local observations only, including expired content"),
5661
+ maxAge: singleton("max-age", "Maximum observation age: 0, Ns, Nm, Nh or Nd; default 5m (list 60s)")
5662
+ };
5663
+ function readPolicy(config) {
5664
+ return Effect14.try({
5665
+ try: () => {
5666
+ const maxAge = Option.getOrUndefined(config.maxAge);
5667
+ if (Number(config.refresh) + Number(config.offline) + Number(maxAge !== undefined) > 1)
5668
+ throw fail("INVALID_ARGUMENT", "--refresh, --offline and --max-age are mutually exclusive.");
5669
+ return {
5670
+ refresh: config.refresh,
5671
+ offline: config.offline,
5672
+ ...maxAge === undefined ? {} : { maxAge: parseDuration(maxAge) }
5673
+ };
5674
+ },
5675
+ catch: (error) => error
5676
+ });
5677
+ }
2934
5678
  function emit(value) {
2935
- return Effect8.gen(function* () {
5679
+ return Effect14.gen(function* () {
2936
5680
  const stdio = yield* Stdio.Stdio;
2937
5681
  yield* Stream3.make(JSON.stringify({ ok: true, ...value }) + `
2938
5682
  `).pipe(Stream3.run(stdio.stdout()));
@@ -2940,12 +5684,12 @@ function emit(value) {
2940
5684
  }
2941
5685
  var listCommand = Command.make("list", {
2942
5686
  database: databaseFlag,
2943
- refresh: refreshFlag,
2944
- query: Flag.String("query").pipe(Flag.optional, Flag.withDescription("Case-insensitive filter on Name, invocation alias and Description"))
2945
- }, (config) => Effect8.gen(function* () {
5687
+ ...readPolicyFlags,
5688
+ query: singleton("query", "Case-insensitive filter on Name, invocation alias and Description")
5689
+ }, (config) => Effect14.gen(function* () {
2946
5690
  const result = yield* catalog({
2947
5691
  database: Option.getOrUndefined(config.database),
2948
- refresh: config.refresh
5692
+ ...yield* readPolicy(config)
2949
5693
  });
2950
5694
  const query = Option.getOrUndefined(config.query)?.toLocaleLowerCase();
2951
5695
  const skills = query ? result.skills.filter((s) => `${s.name}
@@ -2957,9 +5701,11 @@ ${s.description}`.toLocaleLowerCase().includes(query)) : result.skills;
2957
5701
  databases: result.databases,
2958
5702
  skills,
2959
5703
  count: skills.length,
2960
- coverage: result.coverage
5704
+ coverage: result.coverage,
5705
+ source: result.source,
5706
+ freshness: result.freshness
2961
5707
  });
2962
- })).pipe(Command.withShortDescription("List available skills with names, descriptions and refs"), Command.withDescription("List lightweight Skill metadata; follows all Search and data-source pages automatically. Returns databases (ID, title, registered alias and data sources), skills, count and coverage without bodies or file manifests. --query filters Skill Name/alias/Description only and retains the queried database map. --database selects one ID, URL or exact registered alias; repeated values fail. --refresh bypasses the 60-second metadata cache. Failed queries include owning database ID/alias/title and data_source_id in coverage.failed_sources. Search cannot prove workspace-wide completeness."), Command.withExamples([
5708
+ })).pipe(Command.withShortDescription("List available skills with names, descriptions and refs"), Command.withDescription("List paginated lightweight Skill metadata with database maps and coverage. --query filters Name/alias/Description while retaining the database map. Catalog age defaults to 60s; --refresh validates online, --offline uses stored observations, --max-age overrides age. These policies are mutually exclusive. Cache freshness never improves discovery coverage; failed sources stay explicit. --database accepts one ID, URL or exact registered alias; Search is not workspace-exhaustive."), Command.withExamples([
2963
5709
  {
2964
5710
  command: "ntn-skills list",
2965
5711
  description: "Discover accessible skills before selecting a workflow"
@@ -2977,7 +5723,7 @@ ${s.description}`.toLocaleLowerCase().includes(query)) : result.skills;
2977
5723
  description: "Query the database previously registered with source add frontend --database DATABASE_ID"
2978
5724
  }
2979
5725
  ]));
2980
- var databaseList = Command.make("list", { database: databaseFlag }, (config) => Effect8.gen(function* () {
5726
+ var databaseList = Command.make("list", { database: databaseFlag }, (config) => Effect14.gen(function* () {
2981
5727
  const explicit = Option.getOrUndefined(config.database);
2982
5728
  const result = explicit !== undefined ? { databases: [yield* explicitSource(explicit)], failures: [] } : yield* discoverDatabases();
2983
5729
  yield* emit({
@@ -2994,14 +5740,18 @@ var databaseList = Command.make("list", { database: databaseFlag }, (config) =>
2994
5740
  var databaseCommand = Command.make("database").pipe(Command.withShortDescription("Discover Skills Databases"), Command.withSubcommands([databaseList]));
2995
5741
  var openCommand = Command.make("open", {
2996
5742
  selector: Argument.String("target").pipe(Argument.withDescription("Name, invocation alias, page ID/URL, skill:// ref, or cached snapshot ID")),
2997
- database: databaseFlag
2998
- }, (config) => Effect8.gen(function* () {
2999
- const target = yield* Effect8.try({
5743
+ database: databaseFlag,
5744
+ ...readPolicyFlags
5745
+ }, (config) => Effect14.gen(function* () {
5746
+ const target = yield* Effect14.try({
3000
5747
  try: () => parseTarget(config.selector),
3001
5748
  catch: (e) => e
3002
5749
  });
3003
- yield* emit(snapshotInfo(yield* targetSnapshot(target, { database: Option.getOrUndefined(config.database) })));
3004
- })).pipe(Command.withShortDescription("Download a skill into an immutable snapshot"), Command.withDescription("Return complete snapshot metadata and pinned file refs without contents. Uses the shared target syntax: names, aliases, page IDs/URLs and unpinned refs obtain the current export online; pinned refs and snapshot IDs use cached content offline. Normal reads obtain their own snapshot; open is optional. Scripts are never executed."), Command.withExamples([
5750
+ yield* emit(snapshotInfo(yield* targetSnapshot(target, {
5751
+ database: Option.getOrUndefined(config.database),
5752
+ ...yield* readPolicy(config)
5753
+ })));
5754
+ })).pipe(Command.withShortDescription("Download a skill into an immutable snapshot"), Command.withDescription("Return complete snapshot metadata and pinned file refs without contents. Current targets reuse complete eligible observations for 5m by default. --refresh validates online, --offline reads local observations, --max-age overrides age. Pinned refs and snapshot IDs remain immutable and offline; they reject refresh/max-age. Expired online reads wait for validation and never silently fall back to stale content. Normal reads obtain their own snapshot; open is optional. Scripts are never executed."), Command.withExamples([
3005
5755
  {
3006
5756
  command: "ntn-skills open resource-tag-governance",
3007
5757
  description: "Download a current skill and retain its snapshot_id for local reads"
@@ -3009,28 +5759,30 @@ var openCommand = Command.make("open", {
3009
5759
  ]));
3010
5760
  var readCommand = Command.make("read", {
3011
5761
  selector: Argument.String("target").pipe(Argument.withDescription("Name, invocation alias, page ID/URL, skill:// ref, cached snapshot ID, or relative path with --from")),
3012
- path: Flag.String("path").pipe(Flag.optional, Flag.withDescription("Skill-relative file path; target must not already contain a path")),
5762
+ path: singleton("path", "Skill-relative file path; target must not already contain a path"),
3013
5763
  database: databaseFlag,
3014
- from: Flag.String("from").pipe(Flag.optional, Flag.withDescription("Resolve the first argument relative to this containing-file skill:// ref; preserve its snapshot when pinned")),
3015
- lines: Flag.String("lines").pipe(Flag.optional, Flag.withDescription("Inclusive 1-based range START-END or one line START; returns range and has_more; incompatible with --output")),
3016
- output: Flag.String("output").pipe(Flag.optional, Flag.withDescription("Write exact bytes to a local path; reuse identical content, reject differing output; incompatible with --lines/--raw")),
3017
- raw: Flag.Boolean("raw").pipe(Flag.withDefault(false), Flag.withDescription("Emit successful UTF-8 text only; failures remain JSON; retain snapshot/ref separately; incompatible with --output"))
3018
- }, (config) => Effect8.gen(function* () {
5764
+ ...readPolicyFlags,
5765
+ from: singleton("from", "Resolve the first argument relative to this containing-file skill:// ref; preserve its snapshot when pinned"),
5766
+ lines: singleton("lines", "Inclusive 1-based range START-END or one line START; incompatible with --output"),
5767
+ output: singleton("output", "Write exact bytes to a local path; reuse identical content, reject differing output; incompatible with --lines/--raw"),
5768
+ raw: switchFlag("raw", "Emit successful UTF-8 text only; failures remain JSON; incompatible with --output")
5769
+ }, (config) => Effect14.gen(function* () {
3019
5770
  if (config.raw && Option.isSome(config.output))
3020
- return yield* Effect8.fail(fail("INVALID_ARGUMENT", "--raw cannot be combined with --output."));
5771
+ return yield* Effect14.fail(fail("INVALID_ARGUMENT", "--raw cannot be combined with --output."));
3021
5772
  const result = yield* readSkill(config.selector, {
3022
5773
  path: Option.getOrUndefined(config.path),
3023
5774
  database: Option.getOrUndefined(config.database),
3024
5775
  from: Option.getOrUndefined(config.from),
3025
5776
  lines: Option.getOrUndefined(config.lines),
3026
- output: Option.getOrUndefined(config.output)
5777
+ output: Option.getOrUndefined(config.output),
5778
+ ...yield* readPolicy(config)
3027
5779
  });
3028
5780
  if (config.raw) {
3029
5781
  const stdio = yield* Stdio.Stdio;
3030
5782
  yield* Stream3.make("content" in result ? result.content : "").pipe(Stream3.run(stdio.stdout()));
3031
5783
  } else
3032
5784
  yield* emit(result);
3033
- })).pipe(Command.withShortDescription("Read one file online or from a pinned snapshot"), Command.withDescription("Read one file, default SKILL.md. Accepts names, invocation aliases, page IDs/URLs, skill:// refs and snapshot IDs. Pinned refs and snapshot IDs read cached content offline; other targets check the current export online. --path supplies a file only when the target has no path. Relative reads use read relative-path --from containing-file-ref; --from cannot combine with --path. JSON includes content, identity, pinned ref, version, range and has_more. --lines uses inclusive 1-based ranges; --output returns exact bytes, output and reused, rejecting differing local files. --raw emits text only. FILE_NOT_FOUND: inspect files; SNAPSHOT_MISSING: read the current target online; arbitrary historical versions cannot be fetched."), Command.withExamples([
5785
+ })).pipe(Command.withShortDescription("Read one file with bounded cache freshness or a pinned snapshot"), Command.withDescription("Read one file, default SKILL.md. Names/aliases/page IDs/URLs/unpinned refs reuse complete eligible observations for 5m; --refresh validates online, --offline reads local observations, --max-age overrides age. Policies are mutually exclusive. Pinned targets (including relative --from pinned refs) stay immutable/offline and reject refresh/max-age. --path supplies a file only when the target has no path. Relative --from rejects --path. JSON includes source/freshness, identity, pinned ref, version, range and has_more. --lines uses inclusive 1-based ranges. --output writes exact bytes with identical reuse and differing-output rejection; --raw emits successful text only. Missing cached versions require a new current read; arbitrary historical versions cannot be fetched."), Command.withExamples([
3034
5786
  {
3035
5787
  command: "ntn-skills read 'skill://resource-tag-governance/SKILL.md'",
3036
5788
  description: "Read the current entrypoint by invocation name"
@@ -3054,34 +5806,36 @@ var readCommand = Command.make("read", {
3054
5806
  ]));
3055
5807
  var filesCommand = Command.make("files", {
3056
5808
  selector: Argument.String("target").pipe(Argument.withDescription("Name, invocation alias, page ID/URL, skill:// ref, or cached snapshot ID")),
3057
- path: Flag.String("path").pipe(Flag.optional, Flag.withDescription("File/directory filter; omit for every file; cannot replace a ref's path")),
3058
- database: databaseFlag
3059
- }, (config) => Effect8.gen(function* () {
5809
+ path: singleton("path", "File/directory filter; omit for every file; cannot replace a ref's path"),
5810
+ database: databaseFlag,
5811
+ ...readPolicyFlags
5812
+ }, (config) => Effect14.gen(function* () {
3060
5813
  yield* emit(yield* listSkill(config.selector, {
3061
5814
  path: Option.getOrUndefined(config.path),
3062
- database: Option.getOrUndefined(config.database)
5815
+ database: Option.getOrUndefined(config.database),
5816
+ ...yield* readPolicy(config)
3063
5817
  }));
3064
- })).pipe(Command.withShortDescription("List snapshot files and their pinned refs"), Command.withDescription("List pinned file refs without contents using the shared target syntax. Names, aliases, page IDs/URLs and unpinned refs obtain the current export online; pinned refs and snapshot IDs work offline. --path filters one file/directory when the target has no path. A file ref filters its own path; a pathless ref lists every file."), Command.withExamples([
5818
+ })).pipe(Command.withShortDescription("List snapshot files and their pinned refs"), Command.withDescription("List pinned file refs from one complete snapshot. Current targets follow the 5m content policy; use mutually exclusive --refresh, --offline or --max-age. Pinned refs/snapshot IDs work offline and reject refresh/max-age. --path filters one file/directory when the target has no path; a file ref filters itself, a pathless ref lists every file. Source/freshness describe the selected observation, not current access when cached."), Command.withExamples([
3065
5819
  {
3066
5820
  command: "ntn-skills files SNAPSHOT_ID --path references",
3067
5821
  description: "Find attachment paths in the same snapshot"
3068
5822
  }
3069
5823
  ]));
3070
- var dryRunFlag = Flag.Boolean("dry-run").pipe(Flag.withDefault(false), Flag.withDescription("Validate inputs and show the target without uploading or changing Notion"));
5824
+ var dryRunFlag = switchFlag("dry-run", "Validate inputs and show the decision without content or configuration writes");
3071
5825
  var createCommand = Command.make("create", {
3072
5826
  input: Argument.String("input").pipe(Argument.withDescription("Local ZIP, Skill folder or Markdown file")),
3073
5827
  database: databaseFlag,
3074
- name: Flag.String("name").pipe(Flag.optional, Flag.withDescription("English display title overriding source metadata")),
3075
- description: Flag.String("description").pipe(Flag.optional, Flag.withDescription("Override Description; required if source has none")),
5828
+ name: singleton("name", "English display title overriding source metadata"),
5829
+ description: singleton("description", "Override Description; required if source has none"),
3076
5830
  dryRun: dryRunFlag
3077
- }, (config) => Effect8.gen(function* () {
5831
+ }, (config) => Effect14.gen(function* () {
3078
5832
  yield* emit(yield* createSkill(config.input, {
3079
5833
  database: Option.getOrUndefined(config.database),
3080
5834
  name: Option.getOrUndefined(config.name),
3081
5835
  description: Option.getOrUndefined(config.description),
3082
5836
  dryRun: config.dryRun
3083
5837
  }));
3084
- })).pipe(Command.withShortDescription("Create a new Skill from ZIP, folder or Markdown"), Command.withDescription("Create one new Skill; an existing invocation name returns CREATE_CONFLICT before mutation. Shares the same input and preservation rules as import: ZIP, folder or any Markdown filename; portable manifest or SKILL.md/unique Markdown entrypoint; --name/--description override metadata. Extra frontmatter, original bytes and nested paths are retained in a source ZIP. Database priority: --database > configured default > sole discovered Skills Database. --dry-run validates and reports action=create without upload. Success returns a verified snapshot, pinned refs and content_id. Insert, Update and Read content are required. Inspect partial/unknown outcomes before retrying."), Command.withExamples([
5838
+ })).pipe(Command.withShortDescription("Create a new Skill from ZIP, folder or Markdown"), Command.withDescription("Create one new Skill; an existing invocation name returns CREATE_CONFLICT before mutation. Accepts ZIP, folder or Markdown with a portable manifest or SKILL.md/unique Markdown entrypoint; --name/--description override metadata. References Markdown becomes editable child pages and relative links become Notion URLs. Optional Files preserves original bytes, extra frontmatter and other assets; without Files only main/reference Markdown is accepted and export is normalized. Database priority: --database > configured default > sole discovered skill database. --dry-run validates and reports action=create without mutation. Success returns a verified snapshot, pinned refs and content_id. Insert, Update and Read content are required. Inspect partial/unknown outcomes before retrying."), Command.withExamples([
3085
5839
  {
3086
5840
  command: "ntn-skills create ./my-skill --dry-run",
3087
5841
  description: "Preview creation using the configured default or the only discovered database"
@@ -3098,17 +5852,19 @@ var createCommand = Command.make("create", {
3098
5852
  var importCommand = Command.make("import", {
3099
5853
  input: Argument.String("input").pipe(Argument.withDescription("Local ZIP path, Skill folder, or Markdown file with any filename")),
3100
5854
  database: databaseFlag,
3101
- name: Flag.String("name").pipe(Flag.optional, Flag.withDescription("English display title overriding the imported name or filename")),
3102
- description: Flag.String("description").pipe(Flag.optional, Flag.withDescription("Description overriding frontmatter; required when frontmatter has none")),
5855
+ name: singleton("name", "English display title overriding source metadata"),
5856
+ description: singleton("description", "Override Description; required if source has none"),
5857
+ target: singleton("target", "Existing page selector or pinned main-file baseline; preserve its identity without create fallback"),
3103
5858
  dryRun: dryRunFlag
3104
- }, (config) => Effect8.gen(function* () {
5859
+ }, (config) => Effect14.gen(function* () {
3105
5860
  yield* emit(yield* importSkill(config.input, {
3106
5861
  database: Option.getOrUndefined(config.database),
3107
5862
  name: Option.getOrUndefined(config.name),
3108
5863
  description: Option.getOrUndefined(config.description),
3109
- dryRun: config.dryRun
5864
+ dryRun: config.dryRun,
5865
+ target: Option.getOrUndefined(config.target)
3110
5866
  }));
3111
- })).pipe(Command.withShortDescription("Import a Skill, replacing same-name content"), Command.withDescription("Import one ZIP, folder or Markdown file. No matching invocation name creates a page; identical content returns action=reuse and reused=true; different content returns action=update and replaces the existing page body, metadata and entire file set while retaining its page ID. Multiple matches fail with SKILL_AMBIGUOUS. Overwrite checks a fresh remote version before changing content and again before committing uploaded files. Inputs use a portable manifest or SKILL.md/unique top-level Markdown after wrapper removal. --name/--description override metadata; missing descriptions require --description. All source bytes, extra frontmatter, filenames and nested paths are retained in a source ZIP (20 MiB including manifest); input ZIP max 32 MiB, expanded max 128 MiB/10,000 entries. Imported page IDs never choose a target. Database priority: --database > configured default > sole discovered Skills Database. --dry-run reports create/reuse/update without mutation. Success returns a verified snapshot and content_id. Read back partial/unknown outcomes before retrying."), Command.withExamples([
5867
+ })).pipe(Command.withShortDescription("Import a Skill, replacing same-name content"), Command.withDescription("Import one ZIP, folder or Markdown file. Without --target, match the invocation name in the selected creation database: create if absent, reuse identical content, update differing content. --target resolves one existing page and preserves its identity even when imported metadata renames it; missing/inaccessible targets never create. Pinned main targets enforce expected scope/version; reference-file targets fail. --database constrains an explicit target; otherwise priority is --database > configured default > sole discovered database. --name/--description override source metadata. Whole-Skill updates replace the complete file set; omitted reference pages remain available in Notion. Optional Files preserves bytes/assets; page-only mode accepts main/reference Markdown and compares normalized content. Strong validation includes reference edits; read back partial/unknown outcomes before retry. --dry-run validates without content mutation."), Command.withExamples([
3112
5868
  {
3113
5869
  command: "ntn-skills import ./my-skill.zip --dry-run",
3114
5870
  description: "Preview a ZIP import using the default creation database"
@@ -3124,16 +5880,21 @@ var importCommand = Command.make("import", {
3124
5880
  ]));
3125
5881
  var exportCommand = Command.make("export", {
3126
5882
  selector: Argument.String("skill-or-ref-or-snapshot").pipe(Argument.withDescription("Skill name, page ID/URL, skill:// ref, or cached snapshot ID")),
3127
- output: Flag.String("output").pipe(Flag.withDescription("Destination ZIP path or directory; identical output is reused, differing output is never overwritten")),
3128
- format: Flag.Literals("format", ["zip", "directory"]).pipe(Flag.optional, Flag.withDescription("Default: zip for .zip output paths, directory otherwise")),
3129
- database: databaseFlag
3130
- }, (config) => Effect8.gen(function* () {
5883
+ output: requiredSingleton("output", "Destination ZIP or directory; identical content is reused, differing output is never overwritten"),
5884
+ format: singleton("format", "zip or directory; default: zip for .zip outputs"),
5885
+ database: databaseFlag,
5886
+ ...readPolicyFlags
5887
+ }, (config) => Effect14.gen(function* () {
5888
+ const format = Option.getOrUndefined(config.format);
5889
+ if (format !== undefined && format !== "zip" && format !== "directory")
5890
+ return yield* Effect14.fail(fail("INVALID_ARGUMENT", "--format requires zip or directory."));
3131
5891
  yield* emit(yield* exportSkill(config.selector, {
3132
5892
  output: config.output,
3133
- format: Option.getOrUndefined(config.format),
3134
- database: Option.getOrUndefined(config.database)
5893
+ format,
5894
+ database: Option.getOrUndefined(config.database),
5895
+ ...yield* readPolicy(config)
3135
5896
  }));
3136
- })).pipe(Command.withShortDescription("Export a complete reversible Skill as ZIP or folder"), Command.withDescription("Export every Skill file and a versioned .ntn-skills.json manifest. Uses shared targets; pinned refs and snapshot IDs work offline. Original bytes and paths remain exact until current body or metadata edits replace the preserved main file. ZIP entries sort deterministically with fixed timestamps; payload excludes generated remote identities. --output is required; .zip selects ZIP, otherwise directory; --format overrides it. Identical output returns reused=true; differing output returns OUTPUT_CONFLICT. Importing the export reuses identical content or replaces a different same-name Skill. Export never mutates Notion."), Command.withExamples([
5897
+ })).pipe(Command.withShortDescription("Export a complete reversible Skill as ZIP or folder"), Command.withDescription("Export every Skill file and a versioned portable manifest. Current inputs follow the 5m content policy; use mutually exclusive --refresh, --offline or --max-age. Pinned refs and snapshot IDs are immutable/offline and reject refresh/max-age. References links become relative paths; optional Files preserves source bytes, while page-only output is normalized. ZIP entries sort deterministically with fixed timestamps. --output is required; .zip selects ZIP, otherwise directory; --format overrides it. Identical output returns reused=true; differing output returns OUTPUT_CONFLICT. Cache policy changes input selection only, never output overwrite permission. Export never mutates Notion."), Command.withExamples([
3137
5898
  {
3138
5899
  command: "ntn-skills export 'My Workflow' --output ./my-workflow.zip",
3139
5900
  description: "Export an importable deterministic ZIP"
@@ -3145,18 +5906,18 @@ var exportCommand = Command.make("export", {
3145
5906
  ]));
3146
5907
  var writeCommand = Command.make("write", {
3147
5908
  target: Argument.String("skill-or-ref").pipe(Argument.withDescription("Name, invocation alias, page ID/URL, skill:// file ref or snapshot ID; pinned targets are version baselines")),
3148
- path: Flag.String("path").pipe(Flag.optional, Flag.withDescription("Skill-relative file path, default SKILL.md; omit for a file ref")),
3149
- input: Flag.String("input").pipe(Flag.withDescription("Required local file containing the full replacement content")),
5909
+ path: singleton("path", "Skill-relative file path, default SKILL.md; omit for a file ref"),
5910
+ input: requiredSingleton("input", "Local file containing the full replacement content"),
3150
5911
  database: databaseFlag,
3151
5912
  dryRun: dryRunFlag
3152
- }, (config) => Effect8.gen(function* () {
5913
+ }, (config) => Effect14.gen(function* () {
3153
5914
  yield* emit(yield* writeSkill(config.target, {
3154
5915
  path: Option.getOrUndefined(config.path),
3155
5916
  input: config.input,
3156
5917
  database: Option.getOrUndefined(config.database),
3157
5918
  dryRun: config.dryRun
3158
5919
  }));
3159
- })).pipe(Command.withShortDescription("Write one Skill file to Notion"), Command.withDescription("Replace one Skill file using the shared target syntax, default SKILL.md. --path supplies a path only when the target has none. Pinned refs and snapshot IDs are online version baselines; stale versions return WRITE_CONFLICT. Unpinned targets capture the current version. Entry point name/description update properties; notion_page_id must match. Extra frontmatter and nested/binary attachments are retained in the source ZIP; other logical files stay intact. Identical input returns action=unchanged and unchanged=true without upload or mutation. --dry-run reports the target. Success returns a verified snapshot, pinned file ref and previous_version_id. Body, properties and files are separate requests; read back WRITE_PARTIAL/WRITE_OUTCOME_UNKNOWN before retrying."), Command.withExamples([
5920
+ })).pipe(Command.withShortDescription("Write one Skill file to Notion"), Command.withDescription("Replace one Skill file using shared targets, default SKILL.md. --path supplies a path only when the target has none. Pinned refs and snapshot IDs are online version baselines; stale main or reference-page content returns WRITE_CONFLICT. Unpinned targets capture the current version. Entry point name/description update properties; notion_page_id must match. Reference paths update or add editable Notion pages and restore page links. Optional Files retains extra frontmatter and nested/binary assets; page-only mode accepts main/reference Markdown. Other logical files stay intact. Identical input returns action=unchanged and unchanged=true without mutation. --dry-run validates and reports the target. Success returns a verified snapshot, pinned file ref and previous_version_id. Read back WRITE_PARTIAL/WRITE_OUTCOME_UNKNOWN before retrying."), Command.withExamples([
3160
5921
  {
3161
5922
  command: "ntn-skills write 'PINNED_REF' --input ./SKILL.md --dry-run",
3162
5923
  description: "Preview a write using the exact ref returned by read"
@@ -3174,12 +5935,17 @@ var writeCommand = Command.make("write", {
3174
5935
  description: "Select a Skill by display Name and a separate file path"
3175
5936
  }
3176
5937
  ]));
3177
- var configShow = Command.make("show", {}, () => Effect8.gen(function* () {
3178
- yield* emit({ config: publicConfiguration(yield* configuration) });
3179
- })).pipe(Command.withShortDescription("Show local configuration with token presence only"), Command.withDescription("Read local configuration offline. Token values are omitted; token_configured reports a non-empty configured token. Authentication priority: config.token > NOTION_API_TOKEN > existing ntn login. The default database affects create/import only."));
5938
+ var configShow = Command.make("show", {}, () => Effect14.gen(function* () {
5939
+ yield* emit({
5940
+ config: {
5941
+ ...publicConfiguration(yield* configuration),
5942
+ effective_cache_policy: yield* effectiveCachePolicy
5943
+ }
5944
+ });
5945
+ })).pipe(Command.withShortDescription("Show local configuration with token presence only"), Command.withDescription("Read local configuration and effective cache policy offline. Token values are omitted; token_configured reports a non-empty configured token. Authentication priority: config.token > NOTION_API_TOKEN > existing ntn login. The default database affects create/import only; cache policy controls current reads and catalog observations."));
3180
5946
  var configSetDefault = Command.make("set-default", {
3181
5947
  database: Argument.String("database").pipe(Argument.withDescription("Skills Database ID, Notion URL or exact registered alias; validated online and saved as an ID"))
3182
- }, (config) => Effect8.gen(function* () {
5948
+ }, (config) => Effect14.gen(function* () {
3183
5949
  yield* emit({ config: publicConfiguration(yield* setDefaultDatabase(config.database)) });
3184
5950
  })).pipe(Command.withShortDescription("Set the default Skills Database for create/import"), Command.withDescription("Validate a non-trashed Skills Database online and save its canonical ID as default_database. Preserves source registrations; writes local configuration only."), Command.withExamples([
3185
5951
  {
@@ -3187,16 +5953,16 @@ var configSetDefault = Command.make("set-default", {
3187
5953
  description: "Choose the database for future create/import commands"
3188
5954
  }
3189
5955
  ]));
3190
- var configClearDefault = Command.make("clear-default", {}, () => Effect8.gen(function* () {
5956
+ var configClearDefault = Command.make("clear-default", {}, () => Effect14.gen(function* () {
3191
5957
  yield* emit({ config: publicConfiguration(yield* setDefaultDatabase()) });
3192
5958
  })).pipe(Command.withShortDescription("Clear the default creation database"), Command.withDescription("Remove default_database from local configuration offline, preserving source registrations. Create/import will then use the only discovered database or --database."));
3193
5959
  var configSetToken = Command.make("set-token", {
3194
- stdin: Flag.Boolean("stdin").pipe(Flag.withDefault(false), Flag.withDescription("Required: read the token from piped standard input, never command arguments"))
3195
- }, (config) => Effect8.gen(function* () {
5960
+ stdin: switchFlag("stdin", "Required: read the token from piped standard input, never command arguments")
5961
+ }, (config) => Effect14.gen(function* () {
3196
5962
  const stdio = yield* Stdio.Stdio;
3197
5963
  if (!config.stdin || (yield* stdio.stdinIsTerminal))
3198
- return yield* Effect8.fail(fail("INVALID_ARGUMENT", "Pipe the token into config set-token --stdin."));
3199
- const input = yield* stdio.stdin.pipe(Stream3.decodeText(), Stream3.runFold(() => "", (text, chunk) => text + chunk), Effect8.mapError(() => fail("INPUT_FAILED", "Could not read the token from standard input.")));
5964
+ return yield* Effect14.fail(fail("INVALID_ARGUMENT", "Pipe the token into config set-token --stdin."));
5965
+ const input = yield* stdio.stdin.pipe(Stream3.decodeText(), Stream3.runFold(() => "", (text, chunk) => text + chunk), Effect14.mapError(() => fail("INPUT_FAILED", "Could not read the token from standard input.")));
3200
5966
  yield* emit({ config: yield* setToken(input) });
3201
5967
  })).pipe(Command.withShortDescription("Store the token from standard input in local configuration"), Command.withDescription("Read one token from piped stdin with --stdin; trim surrounding whitespace and reject empty/multiple values. Store config.token with private file permissions while preserving sources/default_database. Works offline; no Notion request or credential validation. Output only reports token_configured. Config token takes priority over NOTION_API_TOKEN and existing ntn login."), Command.withExamples([
3202
5968
  {
@@ -3204,7 +5970,7 @@ var configSetToken = Command.make("set-token", {
3204
5970
  description: "Pipe one token from a trusted secret source into this command; do not put it in arguments"
3205
5971
  }
3206
5972
  ]));
3207
- var configClearToken = Command.make("clear-token", {}, () => Effect8.gen(function* () {
5973
+ var configClearToken = Command.make("clear-token", {}, () => Effect14.gen(function* () {
3208
5974
  yield* emit({ config: yield* setToken() });
3209
5975
  })).pipe(Command.withShortDescription("Remove config.token and use environment/ntn login fallback"), Command.withDescription("Remove only the configured token offline, preserving sources/default_database. Future online requests use NOTION_API_TOKEN or existing ntn login. Output never includes a token."), Command.withExamples([
3210
5976
  {
@@ -3212,17 +5978,39 @@ var configClearToken = Command.make("clear-token", {}, () => Effect8.gen(functio
3212
5978
  description: "Remove the configuration token and restore environment/login fallback"
3213
5979
  }
3214
5980
  ]));
5981
+ var configSetCachePolicy = Command.make("set-cache-policy", {
5982
+ readMaxAge: singleton("read-max-age", "Content age limit: 0, Ns, Nm, Nh or Nd (default 5m)"),
5983
+ catalogMaxAge: singleton("catalog-max-age", "Catalog age limit: 0, Ns, Nm, Nh or Nd (default 60s)")
5984
+ }, (config) => Effect14.gen(function* () {
5985
+ const read = Option.getOrUndefined(config.readMaxAge);
5986
+ const catalog = Option.getOrUndefined(config.catalogMaxAge);
5987
+ if (read === undefined && catalog === undefined)
5988
+ return yield* Effect14.fail(fail("INVALID_ARGUMENT", "Provide --read-max-age or --catalog-max-age."));
5989
+ const policy = yield* Effect14.try({
5990
+ try: () => ({
5991
+ ...read === undefined ? {} : { readMaxAge: parseDuration(read) },
5992
+ ...catalog === undefined ? {} : { catalogMaxAge: parseDuration(catalog) }
5993
+ }),
5994
+ catch: (error) => error
5995
+ });
5996
+ yield* emit({ config: yield* configureCachePolicy(policy) });
5997
+ })).pipe(Command.withShortDescription("Save specified cache age defaults offline"));
5998
+ var configClearCachePolicy = Command.make("clear-cache-policy", {}, () => Effect14.gen(function* () {
5999
+ yield* emit({ config: yield* clearCachePolicy });
6000
+ })).pipe(Command.withShortDescription("Restore built-in cache policy without removing content or state"));
3215
6001
  var configCommand = Command.make("config").pipe(Command.withShortDescription("Manage local authentication and database preferences"), Command.withDescription("Configuration: NTN_SKILLS_CONFIG_HOME > XDG_CONFIG_HOME/ntn-skills > ~/.config/ntn-skills. Set config.token via set-token --stdin; clear-token restores environment/login fallback. All output omits token values. default_database applies to create/import. No Notion writes."), Command.withSubcommands([
3216
6002
  configShow,
3217
6003
  configSetToken,
3218
6004
  configClearToken,
3219
6005
  configSetDefault,
3220
- configClearDefault
6006
+ configClearDefault,
6007
+ configSetCachePolicy,
6008
+ configClearCachePolicy
3221
6009
  ]));
3222
6010
  var sourceAdd = Command.make("add", {
3223
6011
  alias: Argument.String("alias").pipe(Argument.withDescription("Exact local database selection alias; independent of Skill invocation names")),
3224
6012
  database: requiredDatabaseFlag
3225
- }, (config) => Effect8.gen(function* () {
6013
+ }, (config) => Effect14.gen(function* () {
3226
6014
  yield* emit({ source: yield* addSource(config.alias, config.database) });
3227
6015
  })).pipe(Command.withShortDescription("Register a Skills Database in local configuration"), Command.withDescription("Validate one Skills Database ID, URL or existing registered alias online and persist its registration in ~/.config/ntn-skills/config.json (or NTN_SKILLS_CONFIG_HOME / XDG_CONFIG_HOME). Use the new alias with --database or config set-default. Exact aliases select one database; database titles are display labels only. Writes local configuration only; registrations supplement discovery. Re-registering a database changes its alias; an alias already used for another database fails."), Command.withExamples([
3228
6016
  {
@@ -3230,7 +6018,7 @@ var sourceAdd = Command.make("add", {
3230
6018
  description: "Register a known database; replace DATABASE_ID with its ID or URL"
3231
6019
  }
3232
6020
  ]));
3233
- var sourceList = Command.make("list", {}, () => Effect8.gen(function* () {
6021
+ var sourceList = Command.make("list", {}, () => Effect14.gen(function* () {
3234
6022
  yield* emit({ sources: yield* configuredSources });
3235
6023
  })).pipe(Command.withShortDescription("List locally registered database sources"), Command.withDescription("Read database registrations from ~/.config/ntn-skills/config.json (or NTN_SKILLS_CONFIG_HOME / XDG_CONFIG_HOME). Works offline. If new configuration is absent, migrates valid legacy state configuration once and preserves a .migrated backup."), Command.withExamples([
3236
6024
  {
@@ -3241,9 +6029,9 @@ var sourceList = Command.make("list", {}, () => Effect8.gen(function* () {
3241
6029
  var sourceCommand = Command.make("source").pipe(Command.withShortDescription("Manage local database registrations"), Command.withDescription("Manage local Skills Database registrations. Configuration: NTN_SKILLS_CONFIG_HOME > XDG_CONFIG_HOME/ntn-skills > ~/.config/ntn-skills. NTN_SKILLS_HOME controls cached state only. No Notion writes."), Command.withSubcommands([sourceAdd, sourceList]));
3242
6030
  var resolveCommand = Command.make("resolve", {
3243
6031
  relative: Argument.String("relative-path").pipe(Argument.withDescription("File path relative to the containing file named by --from; cannot escape the skill root")),
3244
- from: Flag.String("from").pipe(Flag.withDescription("Required containing-file skill:// ref; a pinned snapshot is preserved in the returned ref"))
3245
- }, (config) => Effect8.gen(function* () {
3246
- const ref = yield* Effect8.try({
6032
+ from: requiredSingleton("from", "Containing-file skill:// ref; a pinned snapshot is preserved in the returned ref")
6033
+ }, (config) => Effect14.gen(function* () {
6034
+ const ref = yield* Effect14.try({
3247
6035
  try: () => resolveRef(config.from, config.relative),
3248
6036
  catch: (e) => e
3249
6037
  });
@@ -3254,19 +6042,20 @@ var resolveCommand = Command.make("resolve", {
3254
6042
  description: "Resolve from a nested reference file and retain its fixed version"
3255
6043
  }
3256
6044
  ]));
3257
- var doctorCommand = Command.make("doctor", {}, () => Effect8.gen(function* () {
6045
+ var doctorCommand = Command.make("doctor", {}, () => Effect14.gen(function* () {
3258
6046
  const api = yield* Notion;
3259
6047
  const version = yield* api.version;
3260
6048
  const result = yield* catalog({ refresh: true });
3261
- let exportStatus = {
6049
+ let readStatus = {
3262
6050
  checked: false,
3263
6051
  reason: "No skill is present in the discovered list."
3264
6052
  };
3265
6053
  if (result.skills[0]) {
3266
- const exported = yield* api.request(`v1/ai/skills/${result.skills[0].id}`);
3267
- exportStatus = {
6054
+ const snapshot = yield* openSkill(result.skills[0].id, { refresh: true });
6055
+ readStatus = {
3268
6056
  checked: true,
3269
- available: Boolean(exported && typeof exported === "object" && "version_id" in exported)
6057
+ available: true,
6058
+ storage: snapshot.references ? "references" : "native_skills"
3270
6059
  };
3271
6060
  }
3272
6061
  yield* emit({
@@ -3274,28 +6063,111 @@ var doctorCommand = Command.make("doctor", {}, () => Effect8.gen(function* () {
3274
6063
  authentication: "available",
3275
6064
  skills_databases: result.databases.length,
3276
6065
  skill_count: result.skills.length,
3277
- skills_api: exportStatus,
6066
+ skill_read: readStatus,
3278
6067
  coverage: result.coverage
3279
6068
  });
3280
- })).pipe(Command.withShortDescription("Check ntn, authentication, discovery and export API"), Command.withDescription("Check ntn version, existing authentication, discovery coverage and export API availability. Does not download bodies or start login. Authentication priority: config.token > NOTION_API_TOKEN > existing ntn login. Use config set-token --stdin to configure a token. Inspect coverage.failed_sources and skills_api; checked=false means no Skill was available to probe."), Command.withExamples([
6069
+ })).pipe(Command.withShortDescription("Check ntn, authentication, discovery and Skill reading"), Command.withDescription("Check ntn version, existing authentication, discovery coverage and reading one current Skill. The read caches its files. Does not start login. Authentication priority: config.token > NOTION_API_TOKEN > existing ntn login. Use config set-token --stdin to configure a token. Inspect coverage.failed_sources and skill_read; checked=false means no Skill was available to probe."), Command.withExamples([
3281
6070
  {
3282
6071
  command: "ntn-skills doctor",
3283
6072
  description: "Diagnose the existing connection before online operations"
3284
6073
  }
3285
6074
  ]));
3286
- var root = Command.make("ntn-skills").pipe(Command.withDescription(`Discover and read: list [--query text] returns paginated Skill metadata, database ID/title/alias/data-source maps and coverage. read TARGET [--path file] obtains its own complete snapshot; files TARGET lists supporting paths. Follow the returned pinned ref with read relative-path --from REF. open/resolve are optional advanced helpers. Targets accept Name, invocation alias, page ID/URL, skill:// ref or snapshot ID. Pinned reads/files/exports work offline. --refresh belongs to list metadata only.
3287
-
3288
- Database selection: --database accepts one ID, URL or exact registered alias; repeated values fail. Register with source add frontend --database DATABASE_ID, then use list --database frontend or read NAME --database frontend. Titles are display labels only. Different databases may contain the same Skill name; name ambiguity reports candidates and their database maps. No --database means broad read discovery. Config set-default accepts the same selector and stores its canonical ID for create/import only.
6075
+ var bindingArgument = Argument.String("binding").pipe(Argument.withDescription("Registered binding ID or exact local label"));
6076
+ var syncBindCommand = Command.make("bind", {
6077
+ target: Argument.String("target"),
6078
+ path: requiredSingleton("path", "Logical local Skill directory; an absent ordinary leaf can be initialized"),
6079
+ as: singleton("as", "Unique local binding label; default is the remote invocation alias"),
6080
+ database: databaseFlag,
6081
+ dryRun: dryRunFlag
6082
+ }, (config) => Effect14.gen(function* () {
6083
+ yield* emit(yield* bindSync(config.target, {
6084
+ path: config.path,
6085
+ as: Option.getOrUndefined(config.as),
6086
+ database: Option.getOrUndefined(config.database),
6087
+ dryRun: config.dryRun
6088
+ }));
6089
+ })).pipe(Command.withShortDescription("Bind an existing page to one logical local directory"), Command.withDescription("Registration validates both sides online. Equal contents initialize a confirmed common baseline; differences require sync plan --from local|notion. Bind never copies content or creates a page. Historical targets and dangling links fail; --dry-run saves no binding or baseline."));
6090
+ var syncStatusCommand = Command.make("status", {
6091
+ binding: bindingArgument.pipe(Argument.optional),
6092
+ refresh: refreshFlag
6093
+ }, (config) => Effect14.gen(function* () {
6094
+ yield* emit(yield* syncStatus(Option.getOrUndefined(config.binding), { refresh: config.refresh }));
6095
+ })).pipe(Command.withShortDescription("Inspect one or all bindings; remote observations are provisional by default"), Command.withDescription("Default inspects local content, common baseline and the last cached remote observation without network. --refresh validates remote state online. Neither observation advances a common baseline."));
6096
+ var syncPlanCommand = Command.make("plan", {
6097
+ binding: bindingArgument.pipe(Argument.optional),
6098
+ all: switchFlag("all", "Plan all active bindings with shared-page and real-target checks"),
6099
+ from: singleton("from", "Explicit source local or notion for initialization or conflict resolution"),
6100
+ output: singleton("output", "Reviewable JSON copy; identical copies reused, differing output rejected")
6101
+ }, (config) => Effect14.gen(function* () {
6102
+ const binding = Option.getOrUndefined(config.binding);
6103
+ const from = Option.getOrUndefined(config.from);
6104
+ if (binding === undefined === !config.all || config.all && from !== undefined)
6105
+ return yield* Effect14.fail(fail("INVALID_ARGUMENT", "Provide exactly one binding or --all; --from is single-binding only."));
6106
+ if (from !== undefined && from !== "local" && from !== "notion")
6107
+ return yield* Effect14.fail(fail("INVALID_ARGUMENT", "--from requires local or notion."));
6108
+ yield* emit(yield* planSync(binding, {
6109
+ all: config.all,
6110
+ from,
6111
+ output: Option.getOrUndefined(config.output)
6112
+ }));
6113
+ })).pipe(Command.withShortDescription("Save a strongly checked content-addressed sync plan"), Command.withDescription("Preview without content or baseline changes. One-sided changes select direction; differing two-sided changes fail with a retained conflict plan. --from explicitly resolves initialization/conflict and still enforces all version/path/link checks. Batch plans accept only one candidate per page and can fan out to unchanged copies."));
6114
+ var syncApplyCommand = Command.make("apply", {
6115
+ plan: requiredSingleton("plan", "Exact saved p_<sha256> plan ID or local JSON file")
6116
+ }, (config) => Effect14.gen(function* () {
6117
+ yield* emit(yield* applySync(config.plan));
6118
+ })).pipe(Command.withShortDescription("Revalidate and execute the saved plan with verified readback"), Command.withDescription("All initial preconditions are checked before the first write. Content, baseline, binding, scope or link changes reject the plan. Confirmed convergence advances each baseline; partial/unknown results retain receipts and require reconcile before another apply. There is no force, direction override or global transaction."));
6119
+ var syncReconcileCommand = Command.make("reconcile", { binding: bindingArgument }, (config) => Effect14.gen(function* () {
6120
+ yield* emit(yield* reconcileSync(config.binding));
6121
+ })).pipe(Command.withShortDescription("Read back an unfinished operation without repeating writes"), Command.withDescription("Strongly reads both sides and classifies the recorded intent. Verified convergence may advance the common baseline; divergence retains the old base. Unresolved outcomes stay explicit and fence affected resources."));
6122
+ var syncUnbindCommand = Command.make("unbind", {
6123
+ binding: bindingArgument,
6124
+ dryRun: dryRunFlag
6125
+ }, (config) => Effect14.gen(function* () {
6126
+ yield* emit(yield* unbindSync(config.binding, { dryRun: config.dryRun }));
6127
+ })).pipe(Command.withShortDescription("Deactivate a binding while retaining content, plans, receipts and baseline"));
6128
+ var syncCommand = Command.make("sync").pipe(Command.withShortDescription("Synchronize existing Notion pages and logical local Skill directories"), Command.withSubcommands([
6129
+ syncBindCommand,
6130
+ syncStatusCommand,
6131
+ syncPlanCommand,
6132
+ syncApplyCommand,
6133
+ syncReconcileCommand,
6134
+ syncUnbindCommand
6135
+ ]));
6136
+ var cacheStatusCommand = Command.make("status", {
6137
+ target: Argument.String("target").pipe(Argument.optional),
6138
+ database: databaseFlag
6139
+ }, (config) => Effect14.gen(function* () {
6140
+ yield* emit(yield* cacheStatus(Option.getOrUndefined(config.target), {
6141
+ database: Option.getOrUndefined(config.database)
6142
+ }));
6143
+ })).pipe(Command.withShortDescription("Inspect effective roots and cached observations offline"));
6144
+ var cacheClearCommand = Command.make("clear", {
6145
+ target: Argument.String("target").pipe(Argument.optional),
6146
+ all: switchFlag("all", "Retire disposable observations in every recorded scope"),
6147
+ database: databaseFlag,
6148
+ dryRun: dryRunFlag
6149
+ }, (config) => Effect14.gen(function* () {
6150
+ const target = Option.getOrUndefined(config.target);
6151
+ if (target === undefined === !config.all || config.all && Option.isSome(config.database))
6152
+ return yield* Effect14.fail(fail("INVALID_ARGUMENT", "Provide exactly one target or --all; --database is target-only."));
6153
+ yield* emit(yield* clearCache(target, {
6154
+ all: config.all,
6155
+ database: Option.getOrUndefined(config.database),
6156
+ dryRun: config.dryRun
6157
+ }));
6158
+ })).pipe(Command.withShortDescription("Move selected cache observations to system Trash"), Command.withDescription("Retires disposable latest/catalog observations only. Pinned snapshots, content objects, bindings, plans, receipts and common baselines survive. --dry-run previews entries; unavailable system Trash is an explicit prerequisite failure."));
6159
+ var cacheCommand = Command.make("cache").pipe(Command.withShortDescription("Inspect and retire disposable read observations"), Command.withSubcommands([cacheStatusCommand, cacheClearCommand]));
6160
+ var root = Command.make("ntn-skills").pipe(Command.withDescription(`Discover and read: list returns paginated metadata and coverage; read/open/files/export accept Name, alias, page ID/URL, skill:// ref or cached snapshot. Current content uses complete eligible observations for 5m; list defaults to 60s. Mutually exclusive --refresh, --offline and --max-age control freshness. Expired online reads wait for validation, with no stale-on-error fallback. Pinned targets remain immutable/offline and reject refresh/max-age; follow their supporting files with read relative-path --from REF. Cached identity is credential/workspace/endpoint/database scoped.
3289
6161
 
3290
- Modify and move: create INPUT creates a new Skill and rejects an existing name in the selected database; import INPUT creates, reuses identical content or replaces same-name content in that database. Both accept ZIP, folder or Markdown and preserve source files/extra frontmatter/nested paths. write TARGET --input FILE replaces one file; unchanged input performs no mutation. export TARGET --output PATH writes a complete ZIP or folder, reuses identical output and rejects different output. Use --dry-run for create/import/write. Database priority for create/import: --database > config.default_database > sole discovered database.
6162
+ Modify and move: create INPUT creates a page; import INPUT creates/reuses/replaces by invocation name. import INPUT --target TARGET replaces one existing page without identity redirection or create fallback. write TARGET --input FILE replaces one file using online version checks. References become editable child pages; optional Files preserves source bytes/assets. Export writes a reversible ZIP/folder without overwriting differing output. --dry-run previews create/import/write.
3291
6163
 
3292
- Settings and diagnosis: database list discovers databases without querying Skill rows; source list/add manages registrations; config show/set-default/clear-default owns the creation default. config set-token --stdin/clear-token manages a global plaintext token with private file permissions. Pipe a token from a trusted secret source; never put it in command arguments. Config output exposes token_configured only. doctor checks runtime/auth/API.
6164
+ Synchronize: sync bind TARGET --path DIR registers a logical directory. Differing first binds require sync plan BINDING --from local|notion. Later one-sided changes select direction from the confirmed common baseline; two-sided differences conflict. sync plan --all validates shared-page candidates and fan-out. sync apply --plan PLAN_ID_OR_FILE rechecks versions, baseline/config identity and complete link chains before execution. Baselines advance only after verified convergence. sync status is provisional/offline by default; --refresh observes current remote state. sync reconcile reads unfinished operations without replay; sync unbind retains content and state.
3293
6165
 
3294
- Output: one JSON value on stdout; check ok/error.code. Exit 0 success, 1 operation failure, 2 invalid arguments. Help/version are text; read --raw changes successful content only. No implicit script execution or login. Online access needs Bun and official ntn. Authentication priority: non-empty config.token > NOTION_API_TOKEN > existing ntn login. Clear a stale config token to restore environment/login fallback.
6166
+ Settings: database list discovers databases; source list/add manages exact registrations. config set-default affects create/import only. config set-token --stdin/clear-token manages a private plaintext token; never put credentials in arguments. config set-cache-policy/clear-cache-policy manages age defaults. cache status inspects roots/observations offline; cache clear TARGET|--all moves disposable observations to system Trash while retaining snapshots, objects, bindings, plans and receipts. Doctor always checks online.
3295
6167
 
3296
- Notion Name uses English letters and single spaces, max 64 characters; lowercase/hyphens yield the invocation alias. Configuration: NTN_SKILLS_CONFIG_HOME > XDG_CONFIG_HOME/ntn-skills > ~/.config/ntn-skills. State: NTN_SKILLS_HOME > XDG_STATE_HOME/ntn-skills > ~/.local/state/ntn-skills.
6168
+ Storage: configuration NTN_SKILLS_CONFIG_HOME > XDG_CONFIG_HOME/ntn-skills > ~/.config/ntn-skills; state NTN_SKILLS_HOME > XDG_STATE_HOME/ntn-skills > ~/.local/state/ntn-skills; cache NTN_SKILLS_CACHE_HOME > XDG_CACHE_HOME/ntn-skills > ~/.cache/ntn-skills. Authentication config.token > NOTION_API_TOKEN > existing ntn login. Online operations need official ntn; consumers require Node.js >=22.19.0.
3297
6169
 
3298
- Recovery: ambiguity requires an explicit page/database; CREATE_CONFLICT means use import to replace or select a new name; OUTPUT_CONFLICT needs a different destination; CATALOG_INCOMPLETE requires fixing failed sources; WRITE_CONFLICT requires a fresh read; WRITE_PARTIAL/WRITE_OUTCOME_UNKNOWN requires readback before retry. Help runs offline without writable configuration. Use ntn-skills COMMAND --help for flags and examples.`), Command.withExamples([
6170
+ Output: one JSON value; exit 0 success, 1 operational failure, 2 invalid arguments. Help/version are offline text; read --raw changes successful text only. No automatic scripts/login, interactive conflict decisions or force bypass. WRITE_CONFLICT or stale plans need fresh observation/replanning; WRITE_PARTIAL/WRITE_OUTCOME_UNKNOWN and interrupted sync require readback/reconcile before new writes. Provider commits are not server-atomic. Use ntn-skills COMMAND --help for parameters.`), Command.withExamples([
3299
6171
  {
3300
6172
  command: "ntn-skills list",
3301
6173
  description: "Discover skill names, descriptions and refs without loading bodies"
@@ -3320,19 +6192,21 @@ Recovery: ambiguity requires an explicit page/database; CREATE_CONFLICT means us
3320
6192
  writeCommand,
3321
6193
  configCommand,
3322
6194
  sourceCommand,
6195
+ syncCommand,
6196
+ cacheCommand,
3323
6197
  resolveCommand,
3324
6198
  doctorCommand
3325
6199
  ]));
3326
- var platform = Layer3.mergeAll(NodeServices.layer, NodeHttpClient.layerFetch, StoreLive.pipe(Layer3.provide(NodeServices.layer)));
3327
- var live = NotionLive.pipe(Layer3.provideMerge(platform));
6200
+ var platform = Layer4.mergeAll(NodeServices.layer, NodeHttpClient.layerFetch, StoreLive.pipe(Layer4.provide(NodeServices.layer)), SyncLocalLive.pipe(Layer4.provide(NodeServices.layer)));
6201
+ var live = NotionLive.pipe(Layer4.provideMerge(platform));
3328
6202
  var args = process.argv.length > 2 ? process.argv.slice(2) : ["--help"];
3329
6203
  var formatter = CliOutput.defaultFormatter({ colors: false });
3330
6204
  var requestedHelp = args.includes("--help") || args.includes("-h") || args.length === 0;
3331
- var cliConfiguration = Layer3.mergeAll(CliConfig.layer({ builtIns: [GlobalFlag.Help, GlobalFlag.Version, GlobalFlag.Completions] }), CliOutput.layer({
6205
+ var cliConfiguration = Layer4.mergeAll(CliConfig.layer({ builtIns: [GlobalFlag.Help, GlobalFlag.Version, GlobalFlag.Completions] }), CliOutput.layer({
3332
6206
  ...formatter,
3333
6207
  formatHelpDoc: (doc) => requestedHelp ? formatter.formatHelpDoc(doc) : ""
3334
6208
  }));
3335
- var program = Command.runWith(root, { version, renderErrors: false })(args).pipe(Effect8.catchCause((cause) => Effect8.gen(function* () {
6209
+ var program = Command.runWith(root, { version, renderErrors: false })(args).pipe(Effect14.catchCause((cause) => Effect14.gen(function* () {
3336
6210
  const error = Cause.squash(cause);
3337
6211
  const code = error instanceof SkillsError ? error.code : CliError.isCliError(error) ? "INVALID_ARGUMENT" : "INTERNAL_ERROR";
3338
6212
  const parseErrors = CliError.isCliError(error) && error._tag === "ShowHelp" ? error.errors : [];
@@ -3345,5 +6219,5 @@ var program = Command.runWith(root, { version, renderErrors: false })(args).pipe
3345
6219
  }) + `
3346
6220
  `).pipe(Stream3.run(stdio.stdout()));
3347
6221
  process.exitCode = code === "INVALID_ARGUMENT" ? 2 : 1;
3348
- })), Effect8.provide(Layer3.mergeAll(live, cliConfiguration)));
6222
+ })), Effect14.provide(Layer4.mergeAll(live, cliConfiguration)));
3349
6223
  NodeRuntime.runMain(program, { disableErrorReporting: true });