@remembrance-ai/mcp-server 0.2.8 → 0.2.10

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.
Files changed (3) hide show
  1. package/dist/server.js +934 -131
  2. package/package.json +5 -5
  3. package/server.json +2 -2
package/dist/server.js CHANGED
@@ -8316,13 +8316,13 @@ function inspectPrivateLessonTag(value) {
8316
8316
  return { tag: aliased, counts: {} };
8317
8317
  }
8318
8318
  function pseudonymizeCorrelationId(value) {
8319
- const digest2 = hashValue(
8319
+ const digest3 = hashValue(
8320
8320
  canonicalJson({
8321
8321
  domain: "remembrance-private-lesson-correlation-v1",
8322
8322
  value: normalizePrivateLessonText(value)
8323
8323
  })
8324
8324
  ).slice("sha256:".length);
8325
- return `corr_${digest2.slice(0, 48)}`;
8325
+ return `corr_${digest3.slice(0, 48)}`;
8326
8326
  }
8327
8327
  var CURRENT_PRIVATE_LESSON_REDACTOR_DIGEST = computePrivateLessonRedactorDigest();
8328
8328
  var PRIVATE_LESSON_BROAD_HOLD_REDACTOR_DIGEST = "sha256:e3414b36b1f8d5512e42148c0d06b958c7010bbdb52024bd78ad4e68b0356324";
@@ -8398,7 +8398,7 @@ function privateLessonSupportedRedactorProfiles() {
8398
8398
  }))
8399
8399
  );
8400
8400
  }
8401
- function privateLessonRedactorProfile(version, digest2) {
8401
+ function privateLessonRedactorProfile(version, digest3) {
8402
8402
  if (typeof version !== "string" || !PRIVATE_LESSON_SUPPORTED_REDACTION_VERSIONS.includes(
8403
8403
  version
8404
8404
  )) {
@@ -8406,10 +8406,10 @@ function privateLessonRedactorProfile(version, digest2) {
8406
8406
  "unsupported_redaction_version"
8407
8407
  );
8408
8408
  }
8409
- if (typeof digest2 !== "string") {
8409
+ if (typeof digest3 !== "string") {
8410
8410
  throw new PrivateLessonRedactionProfileError("unsupported_redactor_digest");
8411
8411
  }
8412
- const profile = PRIVATE_LESSON_SUPPORTED_REDACTOR_PROFILES[version]?.[digest2];
8412
+ const profile = PRIVATE_LESSON_SUPPORTED_REDACTOR_PROFILES[version]?.[digest3];
8413
8413
  if (!profile) {
8414
8414
  throw new PrivateLessonRedactionProfileError("unsupported_redactor_digest");
8415
8415
  }
@@ -27299,13 +27299,13 @@ function toolArgumentSchemaLocation(schema, path) {
27299
27299
  const child = schemaObject(properties[segment]);
27300
27300
  if (child) {
27301
27301
  name = Object.keys(properties).find((key) => key === segment);
27302
- next.push(child);
27302
+ if (!next.includes(child)) next.push(child);
27303
27303
  }
27304
27304
  } else if (typeof segment === "number") {
27305
27305
  const child = schemaObject(current.items);
27306
27306
  if (child) {
27307
27307
  name = "[]";
27308
- next.push(child);
27308
+ if (!next.includes(child)) next.push(child);
27309
27309
  }
27310
27310
  }
27311
27311
  }
@@ -27512,7 +27512,7 @@ import { existsSync as existsSync6 } from "node:fs";
27512
27512
  import { mkdir as mkdir5, writeFile as writeFile2 } from "node:fs/promises";
27513
27513
  import { dirname as dirname8 } from "node:path";
27514
27514
  import {
27515
- createHash as createHash6,
27515
+ createHash as createHash7,
27516
27516
  createHmac,
27517
27517
  createPrivateKey as createPrivateKey2,
27518
27518
  generateKeyPairSync,
@@ -30166,9 +30166,29 @@ function normalizeBoundedWriteJsonSchema(schema, name) {
30166
30166
  schema["x-remembrance-validation-rules"] = QUERY_FEEDBACK_VALIDATION_RULES;
30167
30167
  }
30168
30168
  if (name === "capture_learning") {
30169
- schema.oneOf = ["lesson", "private_skill", "preference"].map((field) => ({
30169
+ const replacement = schemaProperty(schema, "replacement_of");
30170
+ const [skillLink, lessonLink] = replacement.anyOf;
30171
+ const branch = (field, extra = {}) => ({
30172
+ type: "object",
30173
+ properties: {
30174
+ contract_version: schemaProperty(schema, "contract_version"),
30175
+ [field]: schemaProperty(schema, field),
30176
+ ...extra
30177
+ },
30178
+ additionalProperties: false,
30170
30179
  required: [field]
30171
- }));
30180
+ });
30181
+ schema.oneOf = [
30182
+ {
30183
+ ...branch("lesson", {
30184
+ capture_id: schemaProperty(schema, "capture_id"),
30185
+ replacement_of: lessonLink
30186
+ }),
30187
+ not: { required: ["capture_id", "replacement_of"] }
30188
+ },
30189
+ branch("private_skill", { replacement_of: skillLink }),
30190
+ branch("preference")
30191
+ ];
30172
30192
  schema.allOf = [
30173
30193
  {
30174
30194
  if: { required: ["replacement_of"] },
@@ -30185,9 +30205,7 @@ function normalizeBoundedWriteJsonSchema(schema, name) {
30185
30205
  }
30186
30206
  }
30187
30207
  ];
30188
- const replacement = schemaProperty(schema, "replacement_of");
30189
30208
  replacement.description = "Optional lineage for a replacement of one retained draft: a complete private skill for a private-skill draft, or a lesson for a held private-lesson draft. It carries audit/context identity only and grants no approval, destination authority, or permission to reuse held content.";
30190
- const [skillLink, lessonLink] = replacement.anyOf;
30191
30209
  schemaProperty(skillLink, "draft_id").description = "Retained encrypted private-skill draft being replaced.";
30192
30210
  schemaProperty(skillLink, "context_source").description = "Audit-only source label: active_task_context or separately inspected, explicitly partial safe_recovery_context. Neither source is submission authority.";
30193
30211
  schemaProperty(skillLink, "recovery_context_id").description = "Omit this field unless the current inspect_private_learning_outbox agent_recovery.arguments.replacement_of supplies this exact ID. Never invent an ID or derive one from a draft, digest, or ordinary recovery_context. A supplied native context ID may establish a new context epoch but grants no approval or authority to reuse held content. safe_recovery_context alone does not require an ID.";
@@ -30641,7 +30659,8 @@ var RECORD_FILE = /^[a-f0-9]{32}\.json$/u;
30641
30659
  var OVERFLOW_FILE = /^[a-f0-9]{16}\.obligations-overflow\.json$/u;
30642
30660
  var LANE_ENVELOPE_KINDS = /* @__PURE__ */ new Map([
30643
30661
  ["private-lesson-outbox-envelope-v1", "private_lesson"],
30644
- ["private-skill-outbox-envelope-v1", "private_skill"]
30662
+ ["private-skill-outbox-envelope-v1", "private_skill"],
30663
+ ["private-skill-outbox-envelope-v2", "private_skill"]
30645
30664
  ]);
30646
30665
  var LANE_KEY_FREE_VERSIONS = /* @__PURE__ */ new Set([
30647
30666
  "private-lesson-outbox-submitted-v1",
@@ -32049,8 +32068,8 @@ async function queuePrivateLessonReplacement(replacementOf, prepared, options =
32049
32068
  }
32050
32069
  if (privateLessonSafetyRecheck(original)) throw refuse("releasable");
32051
32070
  const attempts = original.replacement_attempts ?? [];
32052
- const digest2 = prepared.payload_digest;
32053
- const draftId = privateLessonReplacementDraftId(replacementOf, digest2);
32071
+ const digest3 = prepared.payload_digest;
32072
+ const draftId = privateLessonReplacementDraftId(replacementOf, digest3);
32054
32073
  markCaptureLearningPersisting(draftId);
32055
32074
  const unresolved = await reconcilePrivateLessonTemporaryWrites(
32056
32075
  directory,
@@ -32059,7 +32078,7 @@ async function queuePrivateLessonReplacement(replacementOf, prepared, options =
32059
32078
  if (unresolved.has(draftId) || (await privateLessonQuarantineEntriesForDraft(directory, draftId)).length > 0) {
32060
32079
  throw new CaptureLearningReplayError("capture_reconciliation_required");
32061
32080
  }
32062
- const replay = attempts.includes(digest2);
32081
+ const replay = attempts.includes(digest3);
32063
32082
  const used = replay ? attempts.length : attempts.length + 1;
32064
32083
  if (!replay && privateLessonCapturedForOtherDestination(original, options.destination)) {
32065
32084
  throw refuse("destination_changed", attempts.length);
@@ -32075,7 +32094,7 @@ async function queuePrivateLessonReplacement(replacementOf, prepared, options =
32075
32094
  await writeDraftUnlocked(
32076
32095
  validateDraft({
32077
32096
  ...original,
32078
- replacement_attempts: [...attempts, digest2],
32097
+ replacement_attempts: [...attempts, digest3],
32079
32098
  updated_at: now.toISOString()
32080
32099
  }),
32081
32100
  outbox,
@@ -32159,7 +32178,7 @@ async function retireReplacedPrivateLessonUnlocked(directory, draftId, replaceme
32159
32178
  }
32160
32179
  function acceptedPrivateLessonReplacement(directory, draft) {
32161
32180
  if (draft.state === "submitted") return void 0;
32162
- return (draft.replacement_attempts ?? []).map((digest2) => privateLessonReplacementDraftId(draft.draft_id, digest2)).find(
32181
+ return (draft.replacement_attempts ?? []).map((digest3) => privateLessonReplacementDraftId(draft.draft_id, digest3)).find(
32163
32182
  (replacement) => existsSync2(submittedRecordPath(directory, replacement))
32164
32183
  );
32165
32184
  }
@@ -33283,7 +33302,7 @@ async function rememberPrivateLessonPolicyFloor(binding, options = {}, legacyPol
33283
33302
  binding.organization_audience_hash,
33284
33303
  "organization audience"
33285
33304
  );
33286
- const digest2 = digestHex(
33305
+ const digest3 = digestHex(
33287
33306
  binding.policy_identity_digest ?? binding.policy_digest,
33288
33307
  "policy identity"
33289
33308
  );
@@ -33334,7 +33353,7 @@ async function rememberPrivateLessonPolicyFloor(binding, options = {}, legacyPol
33334
33353
  );
33335
33354
  }
33336
33355
  if (observed.some(
33337
- (item) => item.sequence === binding.policy_sequence && (item.identity_bound && item.digest !== digest2 || !item.identity_bound && !binding.policy_identity_digest && item.digest !== legacyDigest)
33356
+ (item) => item.sequence === binding.policy_sequence && (item.identity_bound && item.digest !== digest3 || !item.identity_bound && !binding.policy_identity_digest && item.digest !== legacyDigest)
33338
33357
  )) {
33339
33358
  throw new PrivateLessonPolicyFloorError(
33340
33359
  "Private lesson policy conflicts at the same sequence.",
@@ -33343,7 +33362,7 @@ async function rememberPrivateLessonPolicyFloor(binding, options = {}, legacyPol
33343
33362
  }
33344
33363
  const identityPath2 = join3(
33345
33364
  directory,
33346
- `.policy-identity.${audience}.${binding.policy_sequence}.${digest2}.json`
33365
+ `.policy-identity.${audience}.${binding.policy_sequence}.${digest3}.json`
33347
33366
  );
33348
33367
  const legacyPath = join3(
33349
33368
  directory,
@@ -51813,9 +51832,9 @@ function pkcs12(b, t, f, callbacks) {
51813
51832
  let covered = t.complete;
51814
51833
  if (f[2]) {
51815
51834
  const mac = f[2].tag === 48 && fields(b, f[2], 3);
51816
- const digest2 = mac && mac[0]?.tag === 48 && fields(b, mac[0], 2);
51817
- const alg = digest2 && digest2[0]?.tag === 48 && fields(b, digest2[0], 2);
51818
- if (!mac || mac.length < 2 || !digest2 || digest2.length !== 2 || !alg || !hex(b, alg[0]) || alg[1] && (alg[1].tag !== 5 || alg[1].body !== alg[1].end) || digest2[1]?.tag !== 4 || digest2[1].body === digest2[1].end || mac[1]?.tag !== 4 || mac[1].body === mac[1].end || mac[2] && (integer(b, mac[2]) ?? 0n) <= 0n)
51835
+ const digest3 = mac && mac[0]?.tag === 48 && fields(b, mac[0], 2);
51836
+ const alg = digest3 && digest3[0]?.tag === 48 && fields(b, digest3[0], 2);
51837
+ if (!mac || mac.length < 2 || !digest3 || digest3.length !== 2 || !alg || !hex(b, alg[0]) || alg[1] && (alg[1].tag !== 5 || alg[1].body !== alg[1].end) || digest3[1]?.tag !== 4 || digest3[1].body === digest3[1].end || mac[1]?.tag !== 4 || mac[1].body === mac[1].end || mac[2] && (integer(b, mac[2]) ?? 0n) <= 0n)
51819
51838
  covered = false;
51820
51839
  }
51821
51840
  const ci = fields(b, f[1], 2);
@@ -62325,27 +62344,289 @@ function inspectBoundedPrivateLearningRoot(input) {
62325
62344
  }
62326
62345
 
62327
62346
  // src/private-skill-native-context.ts
62347
+ import { createHash as createHash4 } from "node:crypto";
62348
+
62349
+ // src/private-skill-native-authority.ts
62328
62350
  import { createHash as createHash3 } from "node:crypto";
62351
+ var PRIVATE_SKILL_NATIVE_AUTHORITY_VERSION = "private-skill-native-authority-v1";
62352
+ var PRIVATE_SKILL_NATIVE_AUTHORITY_TTL_MS = 3e4;
62353
+ var PRIVATE_SKILL_NATIVE_AUTHORITY_COMMAND_MAX_BYTES = 64 * 1024;
62354
+ var DIGEST2 = /^sha256:[a-f0-9]{64}$/u;
62355
+ var DRAFT = /^psd_[A-Za-z0-9_-]{8,96}$/u;
62356
+ var HEADER = /^\/remembrance-context (psd_[A-Za-z0-9_-]{8,96})$/u;
62357
+ var CONTROL = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]|\r(?!\n)/u;
62358
+ var issued = /* @__PURE__ */ new WeakMap();
62359
+ var unproven = Object.freeze({ status: "unproven" });
62360
+ function createPrivateSkillNativeAuthority(sessionId, commandSource, destination, projectPath, options = {}) {
62361
+ try {
62362
+ const command = parseCommand(commandSource);
62363
+ const session = nativeSession(sessionId);
62364
+ const target = parseDestination(destination);
62365
+ const project = projectIdentity(projectPath);
62366
+ const generation = options.generation ?? 0;
62367
+ if (!Number.isSafeInteger(generation) || generation < 0) invalid();
62368
+ const sourceEventDigest = options.sourceEventDigest ?? null;
62369
+ if (sourceEventDigest !== null && !isDigest2(sourceEventDigest)) invalid();
62370
+ const now = options.now ?? Date.now;
62371
+ const instant = now();
62372
+ if (!validTime(instant) || instant > Number.MAX_SAFE_INTEGER - PRIVATE_SKILL_NATIVE_AUTHORITY_TTL_MS)
62373
+ invalid();
62374
+ const capability = Object.freeze(
62375
+ /* @__PURE__ */ Object.create(null)
62376
+ );
62377
+ issued.set(
62378
+ capability,
62379
+ Object.freeze({
62380
+ draft_id: command.draft_id,
62381
+ command_digest: digest(commandSource),
62382
+ source_digest: digest(command.source),
62383
+ destination: target,
62384
+ provenance: Object.freeze({
62385
+ draft_id: command.draft_id,
62386
+ destination: target,
62387
+ session_digest: digest(session),
62388
+ project_digest: project,
62389
+ generation,
62390
+ source_event_digest: sourceEventDigest
62391
+ }),
62392
+ issued_at: instant,
62393
+ expires_at: instant + PRIVATE_SKILL_NATIVE_AUTHORITY_TTL_MS,
62394
+ now
62395
+ })
62396
+ );
62397
+ return Object.freeze({ status: "authorized", ...command, capability });
62398
+ } catch {
62399
+ return unproven;
62400
+ }
62401
+ }
62402
+ function verifyPrivateSkillNativeAuthority(capability, draftId, contextSource, destination) {
62403
+ try {
62404
+ const entry = liveIssuance(capability);
62405
+ if (typeof draftId !== "string" || !DRAFT.test(draftId) || entry.draft_id !== draftId || typeof contextSource !== "string" || contextSource.length > PRIVATE_SKILL_NATIVE_AUTHORITY_COMMAND_MAX_BYTES || Buffer.byteLength(contextSource, "utf8") > PRIVATE_SKILL_NATIVE_AUTHORITY_COMMAND_MAX_BYTES || entry.source_digest !== digest(contextSource))
62406
+ invalid();
62407
+ const target = parseDestination(destination);
62408
+ if (target.api_base_sha256 !== entry.destination.api_base_sha256 || target.credential_sha256 !== entry.destination.credential_sha256)
62409
+ invalid();
62410
+ return entry.provenance;
62411
+ } catch {
62412
+ return invalid();
62413
+ }
62414
+ }
62415
+ function privateSkillNativeAuthorityDraftId(capability) {
62416
+ try {
62417
+ return liveIssuance(capability).draft_id;
62418
+ } catch {
62419
+ return invalid();
62420
+ }
62421
+ }
62422
+ function createPrivateSkillNativeAuthorityRecord(capability, draftId, contextSource, destination, context, preparedContext) {
62423
+ try {
62424
+ const provenance = verifyPrivateSkillNativeAuthority(
62425
+ capability,
62426
+ draftId,
62427
+ contextSource,
62428
+ destination
62429
+ );
62430
+ const identity2 = contextIdentity(context);
62431
+ const prepared = contextIdentity(preparedContext ?? context);
62432
+ if (prepared.source_digest !== digest(contextSource) || prepared.context_digest !== identity2.context_digest)
62433
+ invalid();
62434
+ return Object.freeze({
62435
+ version: PRIVATE_SKILL_NATIVE_AUTHORITY_VERSION,
62436
+ ...identity2,
62437
+ authorized_source_digest: prepared.source_digest,
62438
+ ...provenance,
62439
+ revoked: false
62440
+ });
62441
+ } catch {
62442
+ return invalid();
62443
+ }
62444
+ }
62445
+ function parsePrivateSkillNativeAuthorityRecord(value, draftId, context) {
62446
+ try {
62447
+ const record4 = exactRecord2(value, [
62448
+ "version",
62449
+ "draft_id",
62450
+ "destination",
62451
+ "source_digest",
62452
+ "context_digest",
62453
+ "authorized_source_digest",
62454
+ "session_digest",
62455
+ "project_digest",
62456
+ "generation",
62457
+ "source_event_digest",
62458
+ "revoked"
62459
+ ]);
62460
+ const identity2 = contextIdentity(context);
62461
+ if (record4.version !== PRIVATE_SKILL_NATIVE_AUTHORITY_VERSION || typeof draftId !== "string" || !DRAFT.test(draftId) || record4.draft_id !== draftId || record4.source_digest !== identity2.source_digest || record4.context_digest !== identity2.context_digest || !isDigest2(record4.authorized_source_digest) || !isDigest2(record4.session_digest) || record4.project_digest !== null && !isDigest2(record4.project_digest) || !Number.isSafeInteger(record4.generation) || record4.generation < 0 || record4.source_event_digest !== null && !isDigest2(record4.source_event_digest) || typeof record4.revoked !== "boolean")
62462
+ invalid();
62463
+ return Object.freeze({
62464
+ version: PRIVATE_SKILL_NATIVE_AUTHORITY_VERSION,
62465
+ draft_id: draftId,
62466
+ destination: parseDestination(record4.destination),
62467
+ ...identity2,
62468
+ authorized_source_digest: record4.authorized_source_digest,
62469
+ session_digest: record4.session_digest,
62470
+ project_digest: record4.project_digest,
62471
+ generation: record4.generation,
62472
+ source_event_digest: record4.source_event_digest,
62473
+ revoked: record4.revoked
62474
+ });
62475
+ } catch {
62476
+ return invalid();
62477
+ }
62478
+ }
62479
+ function liveIssuance(capability) {
62480
+ if (typeof capability !== "object" || capability === null) invalid();
62481
+ const entry = issued.get(capability);
62482
+ if (!entry) invalid();
62483
+ const instant = entry.now();
62484
+ if (!validTime(instant) || instant < entry.issued_at || instant >= entry.expires_at) {
62485
+ issued.delete(capability);
62486
+ invalid();
62487
+ }
62488
+ return entry;
62489
+ }
62490
+ function parseCommand(value) {
62491
+ if (typeof value !== "string" || value.length > PRIVATE_SKILL_NATIVE_AUTHORITY_COMMAND_MAX_BYTES || Buffer.byteLength(value, "utf8") > PRIVATE_SKILL_NATIVE_AUTHORITY_COMMAND_MAX_BYTES || /[\uD800-\uDFFF]/u.test(value) || CONTROL.test(value))
62492
+ invalid();
62493
+ const newline = value.indexOf("\n");
62494
+ if (newline < 0) invalid();
62495
+ const header = value.slice(0, newline).replace(/\r$/u, "");
62496
+ const match = HEADER.exec(header);
62497
+ const source = value.slice(newline + 1);
62498
+ if (!match || source.trim().length === 0) invalid();
62499
+ return { draft_id: match[1], source };
62500
+ }
62501
+ function nativeSession(value) {
62502
+ if (typeof value !== "string") invalid();
62503
+ const session = value.trim();
62504
+ if (!session || session.length > 256 || !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u.test(session) || /^(?:unknown|null|undefined|cursor|opencode-session)$/iu.test(session))
62505
+ invalid();
62506
+ return session;
62507
+ }
62508
+ function projectIdentity(value) {
62509
+ if (value === void 0 || value === null) return null;
62510
+ if (typeof value !== "string" || !value.trim() || value.length > 4096 || Buffer.byteLength(value, "utf8") > 4096 || /[\u0000-\u001F\u007F-\u009F\uD800-\uDFFF]/u.test(value))
62511
+ invalid();
62512
+ return digest(value);
62513
+ }
62514
+ function parseDestination(value) {
62515
+ const record4 = exactRecord2(value, ["api_base_sha256", "credential_sha256"]);
62516
+ if (!isDigest2(record4.api_base_sha256) || !isDigest2(record4.credential_sha256))
62517
+ invalid();
62518
+ return Object.freeze({
62519
+ api_base_sha256: record4.api_base_sha256,
62520
+ credential_sha256: record4.credential_sha256
62521
+ });
62522
+ }
62523
+ function contextIdentity(value) {
62524
+ try {
62525
+ const record4 = exactRecord2(value, [
62526
+ "context_id",
62527
+ "source_digest",
62528
+ "context_digest",
62529
+ "inspector_digest",
62530
+ "context",
62531
+ "partial"
62532
+ ]);
62533
+ if (!isDigest2(record4.source_digest) || !isDigest2(record4.context_digest) || typeof record4.context !== "string" || !record4.context.trim() || /[\uD800-\uDFFF]/u.test(record4.context) || record4.context.length > 256 * 1024 || Buffer.byteLength(record4.context, "utf8") > 256 * 1024)
62534
+ invalid();
62535
+ if (record4.context_digest !== digest(record4.context.normalize("NFC").replace(/\r\n?/gu, "\n").trim()))
62536
+ invalid();
62537
+ return {
62538
+ source_digest: record4.source_digest,
62539
+ context_digest: record4.context_digest
62540
+ };
62541
+ } catch {
62542
+ return invalid();
62543
+ }
62544
+ }
62545
+ function exactRecord2(value, keys) {
62546
+ try {
62547
+ const result = exactRecord(value, keys);
62548
+ if (!result) invalid();
62549
+ return result;
62550
+ } catch {
62551
+ return invalid();
62552
+ }
62553
+ }
62554
+ function validTime(value) {
62555
+ return Number.isSafeInteger(value) && value >= 0;
62556
+ }
62557
+ function isDigest2(value) {
62558
+ return typeof value === "string" && DIGEST2.test(value);
62559
+ }
62560
+ function digest(value) {
62561
+ return `sha256:${createHash3("sha256").update(value, "utf8").digest("hex")}`;
62562
+ }
62563
+ function invalid() {
62564
+ throw new Error("native_context_authority_invalid");
62565
+ }
62566
+
62567
+ // src/private-skill-native-context.ts
62329
62568
  var PRIVATE_SKILL_NATIVE_CONTEXT_MAX_BYTES = 256 * 1024;
62330
62569
  var PRIVATE_SKILL_NATIVE_CONTEXT_OMISSION = "[omitted: private recovery context]";
62331
- var DIGEST2 = /^sha256:[a-f0-9]{64}$/u;
62570
+ var DIGEST3 = /^sha256:[a-f0-9]{64}$/u;
62571
+ function privateSkillNativeContextProjection(value) {
62572
+ return Object.freeze({
62573
+ context_id: value.context_id,
62574
+ source_digest: value.source_digest,
62575
+ context_digest: value.context_digest,
62576
+ inspector_digest: value.inspector_digest,
62577
+ context: value.context,
62578
+ partial: value.partial
62579
+ });
62580
+ }
62581
+ function parseRetainedPrivateSkillNativeContext(value, draftId) {
62582
+ const legacy = dataRecord(value, [
62583
+ "context_id",
62584
+ "source_digest",
62585
+ "context_digest",
62586
+ "inspector_digest",
62587
+ "context",
62588
+ "partial"
62589
+ ]);
62590
+ if (legacy) return parsePrivateSkillNativeContext(legacy);
62591
+ const record4 = dataRecord(value, [
62592
+ "context_id",
62593
+ "source_digest",
62594
+ "context_digest",
62595
+ "inspector_digest",
62596
+ "context",
62597
+ "partial",
62598
+ "authority"
62599
+ ]);
62600
+ if (!record4) invalid2("native_context_record_invalid");
62601
+ const context = parsePrivateSkillNativeContext(
62602
+ privateSkillNativeContextProjection(
62603
+ record4
62604
+ )
62605
+ );
62606
+ const authority = parsePrivateSkillNativeAuthorityRecord(
62607
+ record4.authority,
62608
+ draftId,
62609
+ context
62610
+ );
62611
+ return Object.freeze({ ...context, authority });
62612
+ }
62332
62613
  function createPrivateSkillNativeBinding(sessionId, destination) {
62333
62614
  if (typeof sessionId !== "string" || sessionId.length > 256 || !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u.test(sessionId) || /^(?:unknown|null|undefined)$/iu.test(sessionId)) {
62334
- invalid("native_context_binding_invalid");
62615
+ invalid2("native_context_binding_invalid");
62335
62616
  }
62336
62617
  return Object.freeze({
62337
- session_digest: digest(sessionId),
62338
- destination: parseDestination(destination)
62618
+ session_digest: digest2(sessionId),
62619
+ destination: parseDestination2(destination)
62339
62620
  });
62340
62621
  }
62341
62622
  function parsePrivateSkillNativeBinding(value) {
62342
62623
  const record4 = dataRecord(value, ["session_digest", "destination"]);
62343
- if (!record4 || !isDigest2(record4.session_digest)) {
62344
- invalid("native_context_binding_invalid");
62624
+ if (!record4 || !isDigest3(record4.session_digest)) {
62625
+ invalid2("native_context_binding_invalid");
62345
62626
  }
62346
62627
  return Object.freeze({
62347
62628
  session_digest: record4.session_digest,
62348
- destination: parseDestination(record4.destination)
62629
+ destination: parseDestination2(record4.destination)
62349
62630
  });
62350
62631
  }
62351
62632
  function createPrivateSkillNativeContext(rawSource) {
@@ -62383,7 +62664,7 @@ ${inspected.redacted}`;
62383
62664
  return unavailable("native_context_source_too_large", "context");
62384
62665
  const checked = independentlyUnchanged(context, "context");
62385
62666
  if (checked) return checked;
62386
- return available(makeContext(digest(rawSource), context));
62667
+ return available(makeContext(digest2(rawSource), context));
62387
62668
  }
62388
62669
  function parsePrivateSkillNativeContext(value) {
62389
62670
  const record4 = dataRecord(value, [
@@ -62394,12 +62675,12 @@ function parsePrivateSkillNativeContext(value) {
62394
62675
  "context",
62395
62676
  "partial"
62396
62677
  ]);
62397
- if (!record4 || record4.partial !== true || !isDigest2(record4.source_digest) || !isDigest2(record4.context_digest) || !isDigest2(record4.inspector_digest) || !validText(record4.context) || tooLarge(record4.context) || record4.context_digest !== digest(normalizeContext(record4.context)) || record4.context_id !== contextId(
62678
+ if (!record4 || record4.partial !== true || !isDigest3(record4.source_digest) || !isDigest3(record4.context_digest) || !isDigest3(record4.inspector_digest) || !validText(record4.context) || tooLarge(record4.context) || record4.context_digest !== digest2(normalizeContext(record4.context)) || record4.context_id !== contextId(
62398
62679
  record4.source_digest,
62399
62680
  record4.context_digest,
62400
62681
  record4.inspector_digest
62401
62682
  )) {
62402
- invalid("native_context_record_invalid");
62683
+ invalid2("native_context_record_invalid");
62403
62684
  }
62404
62685
  return Object.freeze({
62405
62686
  context_id: record4.context_id,
@@ -62442,7 +62723,7 @@ function isUnchanged(result, expected) {
62442
62723
  return result.status === "complete" && result.outcome === "unchanged" && result.redacted === expected && result.sensitiveMaterial === false && result.sensitiveObjectKeyMaterial === false;
62443
62724
  }
62444
62725
  function makeContext(source_digest, context) {
62445
- const context_digest = digest(normalizeContext(context));
62726
+ const context_digest = digest2(normalizeContext(context));
62446
62727
  return Object.freeze({
62447
62728
  context_id: contextId(
62448
62729
  source_digest,
@@ -62457,13 +62738,13 @@ function makeContext(source_digest, context) {
62457
62738
  });
62458
62739
  }
62459
62740
  function contextId(source, context, inspector) {
62460
- return `pctx_${digest(JSON.stringify(["private-skill-native-context-v1", source, context, inspector])).slice(7)}`;
62741
+ return `pctx_${digest2(JSON.stringify(["private-skill-native-context-v1", source, context, inspector])).slice(7)}`;
62461
62742
  }
62462
62743
  function normalizeContext(value) {
62463
62744
  return value.normalize("NFC").replace(/\r\n?/gu, "\n").trim();
62464
62745
  }
62465
- function digest(value) {
62466
- return `sha256:${createHash3("sha256").update(value, "utf8").digest("hex")}`;
62746
+ function digest2(value) {
62747
+ return `sha256:${createHash4("sha256").update(value, "utf8").digest("hex")}`;
62467
62748
  }
62468
62749
  function validText(value) {
62469
62750
  return typeof value === "string" && value.trim().length > 0 && !/[\uD800-\uDFFF]/u.test(value);
@@ -62471,13 +62752,13 @@ function validText(value) {
62471
62752
  function tooLarge(value) {
62472
62753
  return Buffer.byteLength(value, "utf8") > PRIVATE_SKILL_NATIVE_CONTEXT_MAX_BYTES;
62473
62754
  }
62474
- function isDigest2(value) {
62475
- return typeof value === "string" && DIGEST2.test(value);
62755
+ function isDigest3(value) {
62756
+ return typeof value === "string" && DIGEST3.test(value);
62476
62757
  }
62477
- function parseDestination(value) {
62758
+ function parseDestination2(value) {
62478
62759
  const record4 = dataRecord(value, ["api_base_sha256", "credential_sha256"]);
62479
- if (!record4 || !isDigest2(record4.api_base_sha256) || !isDigest2(record4.credential_sha256)) {
62480
- invalid("native_context_binding_invalid");
62760
+ if (!record4 || !isDigest3(record4.api_base_sha256) || !isDigest3(record4.credential_sha256)) {
62761
+ invalid2("native_context_binding_invalid");
62481
62762
  }
62482
62763
  return Object.freeze({
62483
62764
  api_base_sha256: record4.api_base_sha256,
@@ -62491,7 +62772,7 @@ function dataRecord(value, fields2) {
62491
62772
  return null;
62492
62773
  }
62493
62774
  }
62494
- function invalid(code) {
62775
+ function invalid2(code) {
62495
62776
  const error = new Error(code);
62496
62777
  Object.assign(error, { code });
62497
62778
  throw error;
@@ -63339,6 +63620,10 @@ var PRIVATE_SKILL_OUTBOX_MAX_BYTES = 64 * 1024 * 1024;
63339
63620
  var PRIVATE_SKILL_CAPTURE_HEADROOM_BYTES = 1024 * 1024;
63340
63621
  var PRIVATE_SKILL_SUBMITTED_RECORD_RETENTION_MS = 14 * 24 * 60 * 60 * 1e3;
63341
63622
  var PRIVATE_SKILL_DRAFT_MAX_BYTES = PRIVATE_SKILL_OUTBOX_MAX_BYTES;
63623
+ var PRIVATE_SKILL_NATIVE_EVENT_MAX = Math.floor(
63624
+ PRIVATE_SKILL_DRAFT_MAX_BYTES / Buffer.byteLength(canonicalJson(`sha256:${"0".repeat(64)}`))
63625
+ );
63626
+ var PRIVATE_SKILL_NATIVE_WITHDRAWAL_RESERVE_BYTES = 64;
63342
63627
  var PRIVATE_SKILL_MARKER_MAX_BYTES = 8 * 1024;
63343
63628
  var PRIVATE_SKILL_CAPACITY_STATE_FILE = ".capture-capacity.json";
63344
63629
  var PRIVATE_SKILL_CAPACITY_STATE_MAX_BYTES = 1024;
@@ -63380,6 +63665,7 @@ var PRIVATE_SKILL_DELIVERY_RECORD_MAX = Math.floor(
63380
63665
  PRIVATE_SKILL_DRAFT_MAX_BYTES / PRIVATE_SKILL_DELIVERY_RECORD_MIN_BYTES
63381
63666
  );
63382
63667
  var inProcessDraftLocks = /* @__PURE__ */ new Map();
63668
+ var qualifiedNativeRecoveryContexts = /* @__PURE__ */ new WeakSet();
63383
63669
  var PrivateSkillDraftDeletedError = class extends PrivateSkillDraftUnavailableError {
63384
63670
  constructor(deletedDraftId) {
63385
63671
  super(deletedDraftId);
@@ -63615,6 +63901,11 @@ async function queuePrivateSkillReformulation(draftId, rawCandidate, contextSour
63615
63901
  privateSkillDraftPath(outbox.directory, draftId),
63616
63902
  outbox.encryption
63617
63903
  );
63904
+ await qualifyRequestedNativeRecoveryContext(
63905
+ current,
63906
+ options,
63907
+ outbox.directory
63908
+ );
63618
63909
  const refreshed = refreshPrivateSkillInspector(
63619
63910
  current,
63620
63911
  options.now ?? /* @__PURE__ */ new Date()
@@ -63627,6 +63918,11 @@ async function queuePrivateSkillReformulation(draftId, rawCandidate, contextSour
63627
63918
  options.env
63628
63919
  );
63629
63920
  current = refreshed;
63921
+ await qualifyRequestedNativeRecoveryContext(
63922
+ current,
63923
+ options,
63924
+ outbox.directory
63925
+ );
63630
63926
  }
63631
63927
  const requestedOperationalCause = options.operationalCause === void 0 ? null : parsePrivateSkillOperationalRetryCause(options.operationalCause);
63632
63928
  const duplicateIndex = current.reformulation_attempts.findIndex(
@@ -64211,60 +64507,340 @@ async function bindPrivateSkillNativeContext(draftId, sessionId, destination, op
64211
64507
  return { status: "bound" };
64212
64508
  });
64213
64509
  }
64214
- async function capturePrivateSkillNativeContext(sessionId, source, destination, options = {}) {
64215
- const binding = createPrivateSkillNativeBinding(sessionId, destination);
64510
+ async function preparePrivateSkillNativeContextAuthority(sessionId, commandSource, destination, projectPath, options = {}) {
64511
+ if (typeof options.sourceEventDigest !== "string" || !/^sha256:[a-f0-9]{64}$/u.test(options.sourceEventDigest))
64512
+ return { status: "unproven" };
64513
+ const eventDigest = options.sourceEventDigest;
64514
+ const provisional = createPrivateSkillNativeAuthority(
64515
+ sessionId,
64516
+ commandSource,
64517
+ destination,
64518
+ projectPath,
64519
+ { now: options.authorityNow, sourceEventDigest: eventDigest }
64520
+ );
64521
+ if (provisional.status !== "authorized") return provisional;
64522
+ const access = verifyPrivateSkillNativeAuthority(
64523
+ provisional.capability,
64524
+ provisional.draft_id,
64525
+ provisional.source,
64526
+ destination
64527
+ ).destination;
64216
64528
  const outbox = await readyPrivateSkillOutbox(options, false);
64217
64529
  return withPrivateSkillOutboxLock(outbox.directory, async () => {
64218
- let prepared;
64219
- let count = 0;
64220
- for (const name of await safeOutboxEntries(outbox.directory)) {
64221
- if (!/^psd_[A-Za-z0-9_-]{8,96}\.json$/u.test(name)) continue;
64222
- let current;
64223
- try {
64224
- current = await readPrivateSkillDraftFrom(
64225
- join4(outbox.directory, name),
64226
- outbox.encryption
64227
- );
64228
- } catch {
64229
- continue;
64530
+ assertPrivateSkillDraftIsMutable(outbox.directory, provisional.draft_id);
64531
+ let current = await readPrivateSkillDraftFrom(
64532
+ privateSkillDraftPath(outbox.directory, provisional.draft_id),
64533
+ outbox.encryption
64534
+ );
64535
+ const regrant = current.native_contexts.some(
64536
+ (context) => context.authority?.revoked
64537
+ );
64538
+ if (current.native_authority_state?.issuance_closed)
64539
+ return { status: "unproven" };
64540
+ if (!nativeContextAppendEligible(current) && !regrant || current.attempts !== 0)
64541
+ return { status: "unproven" };
64542
+ assertPrivateSkillReformulationIsLocal(current);
64543
+ const assessment = await assessPrivateSkillDestinationBinding(
64544
+ current.destination_binding,
64545
+ access,
64546
+ outbox.directory
64547
+ );
64548
+ if (assessment.status !== "matched") return { status: "unproven" };
64549
+ const events = current.native_authority_state?.prepared_events ?? [];
64550
+ if (events.includes(eventDigest)) return { status: "unproven" };
64551
+ const initialized = validatePrivateSkillDraft(
64552
+ {
64553
+ ...current,
64554
+ native_authority_state: {
64555
+ version: "private-skill-native-authority-state-v1",
64556
+ generation: current.native_authority_state?.generation ?? 0,
64557
+ prepared_events: [...events, eventDigest],
64558
+ issuance_closed: false
64559
+ },
64560
+ updated_at: (options.now ?? /* @__PURE__ */ new Date()).toISOString()
64561
+ },
64562
+ current,
64563
+ { nativeAuthorityTransition: "prepare" }
64564
+ );
64565
+ await writePrivateSkillDraft(
64566
+ initialized,
64567
+ outbox.directory,
64568
+ outbox.encryption,
64569
+ options.env
64570
+ );
64571
+ current = initialized;
64572
+ return createPrivateSkillNativeAuthority(
64573
+ sessionId,
64574
+ commandSource,
64575
+ access,
64576
+ projectPath,
64577
+ {
64578
+ now: options.authorityNow,
64579
+ generation: current.native_authority_state.generation,
64580
+ sourceEventDigest: eventDigest
64230
64581
  }
64231
- if (current.attempts !== 0 || current.state !== "held_validation" || current.reformulation_status !== "attempts_exhausted" || !privateSkillHasPositiveRecoveryOutcome(current))
64232
- continue;
64233
- const destinationAssessment = await assessPrivateSkillDestinationBinding(
64234
- current.destination_binding,
64235
- destination,
64236
- outbox.directory
64582
+ );
64583
+ });
64584
+ }
64585
+ async function revokePrivateSkillNativeContextAuthority(draftId, options = {}) {
64586
+ assertPrivateSkillDraftId(draftId);
64587
+ if (options.sourceEventDigest !== void 0 && !/^sha256:[a-f0-9]{64}$/u.test(options.sourceEventDigest))
64588
+ throw new Error("native_context_authority_source_event_invalid");
64589
+ const outbox = await readyPrivateSkillOutbox(options, false);
64590
+ return withPrivateSkillOutboxLock(outbox.directory, async () => {
64591
+ assertPrivateSkillDraftIsMutable(outbox.directory, draftId);
64592
+ const current = await readPrivateSkillDraftFrom(
64593
+ privateSkillDraftPath(outbox.directory, draftId),
64594
+ outbox.encryption
64595
+ );
64596
+ const generation = (current.native_authority_state?.generation ?? 0) + 1;
64597
+ const events = current.native_authority_state?.prepared_events ?? [];
64598
+ if (current.native_authority_state?.issuance_closed)
64599
+ return { status: "revoked" };
64600
+ if (options.sourceEventDigest && events.includes(options.sourceEventDigest))
64601
+ return { status: "revoked" };
64602
+ if (!Number.isSafeInteger(generation))
64603
+ throw new Error("native_context_authority_generation_exhausted");
64604
+ const nextFor = (closed, retainedEvents) => validatePrivateSkillDraft(
64605
+ {
64606
+ ...current,
64607
+ native_authority_state: {
64608
+ version: "private-skill-native-authority-state-v1",
64609
+ generation,
64610
+ prepared_events: retainedEvents,
64611
+ issuance_closed: closed
64612
+ },
64613
+ native_contexts: current.native_contexts.map(
64614
+ (context) => context.authority ? Object.freeze({
64615
+ ...context,
64616
+ authority: Object.freeze({
64617
+ ...context.authority,
64618
+ revoked: true
64619
+ })
64620
+ }) : context
64621
+ ),
64622
+ updated_at: (options.now ?? /* @__PURE__ */ new Date()).toISOString()
64623
+ },
64624
+ current,
64625
+ { nativeAuthorityTransition: "revoke" }
64626
+ );
64627
+ const publish = (next) => writePrivateSkillDraft(
64628
+ next,
64629
+ outbox.directory,
64630
+ outbox.encryption,
64631
+ options.env,
64632
+ () => assertPrivateSkillDraftIsMutable(outbox.directory, draftId),
64633
+ true
64634
+ );
64635
+ try {
64636
+ await publish(
64637
+ nextFor(
64638
+ false,
64639
+ options.sourceEventDigest ? [...events, options.sourceEventDigest] : events
64640
+ )
64237
64641
  );
64238
- if (destinationAssessment.status !== "matched") continue;
64239
- prepared ??= createPrivateSkillNativeContext(source);
64240
- if (prepared.status !== "available")
64241
- return { status: "unavailable", count, reason_code: prepared.code };
64242
- const context = prepared.context;
64243
- if (current.native_contexts.some(
64244
- (entry) => entry.source_digest === context.source_digest || entry.context_digest === context.context_digest
64245
- ))
64246
- continue;
64247
- const next = validatePrivateSkillDraft(
64642
+ } catch (error) {
64643
+ if (!(error instanceof PrivateOutboxCapacityError) && !(error instanceof Error && error.message === "Private skill draft exceeds its encrypted size limit."))
64644
+ throw error;
64645
+ await publish(nextFor(true, events));
64646
+ }
64647
+ return { status: "revoked" };
64648
+ });
64649
+ }
64650
+ function nativeContextAppendEligible(draft) {
64651
+ return draft.attempts === 0 && draft.state === "held_validation" && draft.reformulation_status === "attempts_exhausted" && privateSkillHasPositiveRecoveryOutcome(draft);
64652
+ }
64653
+ async function capturePrivateSkillNativeContext(sessionId, source, destination, options = {}) {
64654
+ if (!options.nativeAuthority)
64655
+ return {
64656
+ status: "ignored",
64657
+ count: 0,
64658
+ reason_code: "native_context_applicability_unproven"
64659
+ };
64660
+ const capability = options.nativeAuthority;
64661
+ let draftId;
64662
+ let binding;
64663
+ try {
64664
+ draftId = privateSkillNativeAuthorityDraftId(capability);
64665
+ binding = createPrivateSkillNativeBinding(sessionId, destination);
64666
+ const provenance = verifyPrivateSkillNativeAuthority(
64667
+ capability,
64668
+ draftId,
64669
+ source,
64670
+ binding.destination
64671
+ );
64672
+ if (provenance.session_digest !== binding.session_digest)
64673
+ return {
64674
+ status: "ignored",
64675
+ count: 0,
64676
+ reason_code: "native_context_applicability_unproven"
64677
+ };
64678
+ } catch {
64679
+ return {
64680
+ status: "ignored",
64681
+ count: 0,
64682
+ reason_code: "native_context_applicability_unproven"
64683
+ };
64684
+ }
64685
+ const access = binding.destination;
64686
+ const outbox = await readyPrivateSkillOutbox(options, false);
64687
+ return withPrivateSkillOutboxLock(outbox.directory, async () => {
64688
+ let generation;
64689
+ let preparedEvents = [];
64690
+ let issuanceClosed = false;
64691
+ const recheck = () => {
64692
+ const provenance = verifyPrivateSkillNativeAuthority(
64693
+ capability,
64694
+ draftId,
64695
+ source,
64696
+ access
64697
+ );
64698
+ if (issuanceClosed || provenance.session_digest !== binding.session_digest || generation !== void 0 && (provenance.generation !== generation || provenance.source_event_digest !== null && !preparedEvents.includes(provenance.source_event_digest)))
64699
+ throw new Error("native_context_authority_invalid");
64700
+ assertPrivateSkillDraftIsMutable(outbox.directory, draftId);
64701
+ };
64702
+ recheck();
64703
+ const current = await readPrivateSkillDraftFrom(
64704
+ privateSkillDraftPath(outbox.directory, draftId),
64705
+ outbox.encryption
64706
+ );
64707
+ generation = current.native_authority_state?.generation ?? 0;
64708
+ preparedEvents = current.native_authority_state?.prepared_events ?? [];
64709
+ issuanceClosed = current.native_authority_state?.issuance_closed ?? false;
64710
+ recheck();
64711
+ if (current.attempts !== 0) return { status: "ignored", count: 0 };
64712
+ if (!nativeContextAppendEligible(current) && !current.native_contexts.some((entry) => entry.authority?.revoked))
64713
+ return { status: "ignored", count: 0 };
64714
+ const assessment = await assessPrivateSkillDestinationBinding(
64715
+ current.destination_binding,
64716
+ access,
64717
+ outbox.directory
64718
+ );
64719
+ if (assessment.status !== "matched") return { status: "ignored", count: 0 };
64720
+ recheck();
64721
+ const prepared = createPrivateSkillNativeContext(source);
64722
+ if (prepared.status !== "available")
64723
+ return { status: "unavailable", count: 0, reason_code: prepared.code };
64724
+ const context = prepared.context;
64725
+ const existing = current.native_contexts.find(
64726
+ (entry) => entry.source_digest === context.source_digest || entry.context_digest === context.context_digest
64727
+ );
64728
+ if (existing) {
64729
+ if (!existing.authority?.revoked) return { status: "ignored", count: 0 };
64730
+ assertPrivateSkillReformulationIsLocal(current);
64731
+ const checked = reviewPrivateSkillNativeContext(
64732
+ privateSkillNativeContextProjection(existing)
64733
+ );
64734
+ if (checked.status !== "available" || existing.context_digest !== context.context_digest)
64735
+ return {
64736
+ status: "unavailable",
64737
+ count: 0,
64738
+ reason_code: "native_context_regrant_mismatch"
64739
+ };
64740
+ const authority2 = createPrivateSkillNativeAuthorityRecord(
64741
+ capability,
64742
+ draftId,
64743
+ source,
64744
+ access,
64745
+ privateSkillNativeContextProjection(existing),
64746
+ context
64747
+ );
64748
+ const regranted = validatePrivateSkillDraft(
64248
64749
  {
64249
64750
  ...current,
64250
- native_binding: current.native_binding ?? binding,
64251
- native_contexts: [...current.native_contexts, context],
64751
+ native_contexts: current.native_contexts.map(
64752
+ (entry) => entry === existing ? Object.freeze({ ...entry, authority: authority2 }) : entry
64753
+ ),
64252
64754
  updated_at: (options.now ?? /* @__PURE__ */ new Date()).toISOString()
64253
64755
  },
64254
64756
  current,
64255
- { nativeContextObserved: true }
64757
+ { nativeAuthorityTransition: "regrant" }
64256
64758
  );
64257
64759
  await writePrivateSkillDraft(
64258
- next,
64760
+ regranted,
64259
64761
  outbox.directory,
64260
64762
  outbox.encryption,
64261
- options.env
64763
+ options.env,
64764
+ recheck
64262
64765
  );
64263
- count++;
64766
+ return { status: "regranted", count: 0 };
64264
64767
  }
64265
- return { status: count ? "recorded" : "ignored", count };
64768
+ if (!nativeContextAppendEligible(current))
64769
+ return { status: "ignored", count: 0 };
64770
+ const authority = createPrivateSkillNativeAuthorityRecord(
64771
+ capability,
64772
+ draftId,
64773
+ source,
64774
+ access,
64775
+ context
64776
+ );
64777
+ const next = validatePrivateSkillDraft(
64778
+ {
64779
+ ...current,
64780
+ destination_binding: assessment.binding,
64781
+ native_authority_state: current.native_authority_state ?? {
64782
+ version: "private-skill-native-authority-state-v1",
64783
+ generation: 0,
64784
+ prepared_events: [],
64785
+ issuance_closed: false
64786
+ },
64787
+ native_binding: current.native_binding ?? binding,
64788
+ native_contexts: [
64789
+ ...current.native_contexts,
64790
+ Object.freeze({ ...context, authority })
64791
+ ],
64792
+ updated_at: (options.now ?? /* @__PURE__ */ new Date()).toISOString()
64793
+ },
64794
+ current,
64795
+ {
64796
+ nativeContextObserved: true,
64797
+ nativeAuthorityTransition: "append",
64798
+ allowDestinationAudienceUpgrade: true
64799
+ }
64800
+ );
64801
+ await writePrivateSkillDraft(
64802
+ next,
64803
+ outbox.directory,
64804
+ outbox.encryption,
64805
+ options.env,
64806
+ recheck
64807
+ );
64808
+ return { status: "recorded", count: 1 };
64266
64809
  });
64267
64810
  }
64811
+ async function qualifyNativeRecoveryContext(draft, context, destination, directory) {
64812
+ if (!context.authority) return;
64813
+ if (context.authority.revoked || context.authority.generation !== draft.native_authority_state?.generation)
64814
+ throw new PrivateSkillRecoveryContextError(draft.draft_id, "unavailable");
64815
+ const current = await assessPrivateSkillDestinationBinding(
64816
+ draft.destination_binding,
64817
+ destination,
64818
+ directory
64819
+ );
64820
+ const source = await assessPrivateSkillDestinationBinding(
64821
+ draft.destination_binding,
64822
+ context.authority.destination,
64823
+ directory
64824
+ );
64825
+ if (current.status !== "matched" || source.status !== "matched")
64826
+ throw new PrivateSkillRecoveryContextError(draft.draft_id, "unavailable");
64827
+ qualifiedNativeRecoveryContexts.add(context);
64828
+ }
64829
+ async function qualifyRequestedNativeRecoveryContext(draft, options, directory) {
64830
+ if (!options.recoveryContextId) return;
64831
+ const context = draft.native_contexts.find(
64832
+ (entry) => entry.context_id === options.recoveryContextId
64833
+ );
64834
+ if (!context?.authority) return;
64835
+ if (!options.destination)
64836
+ throw new PrivateSkillRecoveryContextError(draft.draft_id, "unavailable");
64837
+ await qualifyNativeRecoveryContext(
64838
+ draft,
64839
+ context,
64840
+ parsePrivateSkillDestination(options.destination),
64841
+ directory
64842
+ );
64843
+ }
64268
64844
  function verifiedNativeRecoveryContext(draft, contextId2, allowCurrentEpoch = false) {
64269
64845
  const retained = draft.native_contexts.find(
64270
64846
  (context) => context.context_id === contextId2
@@ -64273,7 +64849,11 @@ function verifiedNativeRecoveryContext(draft, contextId2, allowCurrentEpoch = fa
64273
64849
  (epoch) => epoch.authorized_context_identity === retained.context_digest
64274
64850
  ) && (!allowCurrentEpoch || draft.recovery_epochs.epochs.at(-1)?.authorized_context_identity !== retained.context_digest))
64275
64851
  throw new PrivateSkillRecoveryContextError(draft.draft_id, "unavailable");
64276
- const checked = reviewPrivateSkillNativeContext(retained);
64852
+ if (retained.authority && (retained.authority.revoked || retained.authority.generation !== draft.native_authority_state?.generation || !qualifiedNativeRecoveryContexts.has(retained)))
64853
+ throw new PrivateSkillRecoveryContextError(draft.draft_id, "unavailable");
64854
+ const checked = reviewPrivateSkillNativeContext(
64855
+ privateSkillNativeContextProjection(retained)
64856
+ );
64277
64857
  if (checked.status !== "available")
64278
64858
  throw new PrivateSkillRecoveryContextError(
64279
64859
  draft.draft_id,
@@ -64285,6 +64865,7 @@ function selectPrivateSkillNativeRecoveryContext(draft) {
64285
64865
  if (draft.attempts !== 0 || draft.state !== "held_validation" || draft.reformulation_status !== "attempts_exhausted")
64286
64866
  return null;
64287
64867
  for (const context of [...draft.native_contexts].reverse()) {
64868
+ if (context.authority) continue;
64288
64869
  try {
64289
64870
  return {
64290
64871
  ...verifiedNativeRecoveryContext(draft, context.context_id),
@@ -64295,10 +64876,46 @@ function selectPrivateSkillNativeRecoveryContext(draft) {
64295
64876
  }
64296
64877
  return null;
64297
64878
  }
64879
+ async function readPrivateSkillNativeRecoveryContext(draftId, destination, options = {}) {
64880
+ assertPrivateSkillDraftId(draftId);
64881
+ const access = parsePrivateSkillDestination(destination);
64882
+ const outbox = await readyPrivateSkillOutbox(options, false);
64883
+ return withPrivateSkillOutboxLock(outbox.directory, async () => {
64884
+ assertPrivateSkillDraftIsMutable(outbox.directory, draftId);
64885
+ const draft = await readPrivateSkillDraftFrom(
64886
+ privateSkillDraftPath(outbox.directory, draftId),
64887
+ outbox.encryption
64888
+ );
64889
+ if (draft.attempts !== 0 || draft.state !== "held_validation" || draft.reformulation_status !== "attempts_exhausted")
64890
+ return null;
64891
+ const assessment = await assessPrivateSkillDestinationBinding(
64892
+ draft.destination_binding,
64893
+ access,
64894
+ outbox.directory
64895
+ );
64896
+ if (assessment.status !== "matched") return null;
64897
+ for (const context of [...draft.native_contexts].reverse()) {
64898
+ try {
64899
+ await qualifyNativeRecoveryContext(
64900
+ draft,
64901
+ context,
64902
+ access,
64903
+ outbox.directory
64904
+ );
64905
+ return Object.freeze({
64906
+ ...verifiedNativeRecoveryContext(draft, context.context_id),
64907
+ context_id: context.context_id
64908
+ });
64909
+ } catch {
64910
+ }
64911
+ }
64912
+ return null;
64913
+ });
64914
+ }
64298
64915
  function hasPendingNativeContext(draft) {
64299
64916
  return draft.attempts === 0 && draft.state === "held_validation" && draft.reformulation_status === "attempts_exhausted" && privateSkillHasPositiveRecoveryOutcome(draft) && Boolean(
64300
64917
  draft.native_binding && draft.native_contexts.some(
64301
- (context) => !draft.recovery_epochs?.epochs.some(
64918
+ (context) => !context.authority?.revoked && (!context.authority || context.authority.generation === draft.native_authority_state?.generation) && !draft.recovery_epochs?.epochs.some(
64302
64919
  (epoch) => epoch.authorized_context_identity === context.context_digest
64303
64920
  )
64304
64921
  )
@@ -65189,7 +65806,7 @@ async function ensurePrivateDirectory(path) {
65189
65806
  }
65190
65807
  await chmod3(path, 448);
65191
65808
  }
65192
- async function writePrivateSkillDraft(draft, directory, encryption, env = process.env) {
65809
+ async function writePrivateSkillDraft(draft, directory, encryption, env = process.env, beforePublish, withdrawal = false) {
65193
65810
  const parsed = validatePrivateSkillDraft(draft);
65194
65811
  const metadata = envelopeMetadata(parsed);
65195
65812
  const nonce = randomBytes6(12);
@@ -65212,7 +65829,8 @@ async function writePrivateSkillDraft(draft, directory, encryption, env = proces
65212
65829
  const encoded = `${canonicalJson(envelope)}
65213
65830
  `;
65214
65831
  const encodedBytes = Buffer.byteLength(encoded);
65215
- if (encodedBytes > PRIVATE_SKILL_DRAFT_MAX_BYTES) {
65832
+ const reserve = parsed.native_authority_state && !withdrawal ? PRIVATE_SKILL_NATIVE_WITHDRAWAL_RESERVE_BYTES : 0;
65833
+ if (encodedBytes + reserve > PRIVATE_SKILL_DRAFT_MAX_BYTES) {
65216
65834
  throw new Error("Private skill draft exceeds its encrypted size limit.");
65217
65835
  }
65218
65836
  const path = privateSkillDraftPath(directory, parsed.draft_id);
@@ -65225,7 +65843,8 @@ async function writePrivateSkillDraft(draft, directory, encryption, env = proces
65225
65843
  });
65226
65844
  const projectedBytes = await retainedPrivateSkillOutboxBytes(directory) - currentSize + encodedBytes;
65227
65845
  const ceilingBytes = privateSkillOutboxMaxBytes(env);
65228
- if (projectedBytes > ceilingBytes) {
65846
+ const nonGrowingWithdrawal = withdrawal && currentSize > 0 && encodedBytes <= currentSize;
65847
+ if (projectedBytes + reserve > ceilingBytes && !nonGrowingWithdrawal) {
65229
65848
  if (currentSize === 0) {
65230
65849
  await recordPrivateSkillCapacityRejection(directory, encodedBytes).catch(
65231
65850
  () => {
@@ -65238,7 +65857,7 @@ async function writePrivateSkillDraft(draft, directory, encryption, env = proces
65238
65857
  "would be exceeded"
65239
65858
  );
65240
65859
  }
65241
- await atomicWritePrivateText(path, encoded);
65860
+ await atomicWritePrivateText(path, encoded, beforePublish);
65242
65861
  }
65243
65862
  async function readPrivateSkillDraftFrom(path, encryption) {
65244
65863
  const envelope = parseEnvelope2(
@@ -65266,6 +65885,8 @@ async function readPrivateSkillDraftFrom(path, encryption) {
65266
65885
  throw new PrivateOutboxDecryptionError("private_skill", envelope.draft_id);
65267
65886
  }
65268
65887
  const parsed = validatePrivateSkillDraft(JSON.parse(plaintext));
65888
+ if (envelope.version === "private-skill-outbox-envelope-v2" !== Boolean(parsed.native_authority_state))
65889
+ throw new Error("Private skill native authority envelope is invalid.");
65269
65890
  if (parsed.draft_id !== envelope.draft_id || parsed.state !== envelope.state || parsed.candidate_digest !== envelope.candidate_digest || parsed.next_retry_at !== envelope.next_retry_at || parsed.created_at !== envelope.created_at || parsed.updated_at !== envelope.updated_at) {
65270
65891
  throw new Error(
65271
65892
  "Private skill outbox metadata does not match its payload."
@@ -65412,7 +66033,15 @@ function validatePrivateSkillDraft(value, previous, options = {}) {
65412
66033
  // Absent, not null, on drafts that never had one.
65413
66034
  ...destinationCapabilityHold ? { destination_capability_hold: destinationCapabilityHold } : {},
65414
66035
  native_binding: value.native_binding == null ? null : parsePrivateSkillNativeBinding(value.native_binding),
65415
- native_contexts: parseRetainedNativeContexts(value.native_contexts),
66036
+ ...value.native_authority_state === void 0 ? {} : {
66037
+ native_authority_state: parsePrivateSkillNativeAuthorityState(
66038
+ value.native_authority_state
66039
+ )
66040
+ },
66041
+ native_contexts: parseRetainedNativeContexts(
66042
+ value.native_contexts,
66043
+ draftId
66044
+ ),
65416
66045
  selected_reformulation_attempt: selectedReformulationAttempt,
65417
66046
  source_projections: sourceProjections,
65418
66047
  selected_source_projection: selectedSourceProjection,
@@ -65430,6 +66059,13 @@ function validatePrivateSkillDraft(value, previous, options = {}) {
65430
66059
  }
65431
66060
  if (draft.native_contexts.length > 0 && !draft.native_binding)
65432
66061
  throw new Error("Private skill native context has no task binding.");
66062
+ const preparedNativeEvents = new Set(
66063
+ draft.native_authority_state?.prepared_events ?? []
66064
+ );
66065
+ if (draft.native_contexts.some(
66066
+ (context) => context.authority && (!draft.native_authority_state || draft.native_authority_state.issuance_closed && !context.authority.revoked || context.authority.source_event_digest !== null && !preparedNativeEvents.has(context.authority.source_event_digest) || context.authority.generation > draft.native_authority_state.generation || !context.authority.revoked && context.authority.generation !== draft.native_authority_state.generation)
66067
+ ))
66068
+ throw new Error("Private skill native authority generation is invalid.");
65433
66069
  validatePrivateSkillReformulationState(draft);
65434
66070
  validatePrivateSkillSourceProjectionState(draft);
65435
66071
  validatePrivateSkillDeliveryState(
@@ -65439,7 +66075,15 @@ function validatePrivateSkillDraft(value, previous, options = {}) {
65439
66075
  validatePrivateSkillDestinationRejection(draft);
65440
66076
  if (previous) {
65441
66077
  const transition = options.transition ?? "preserve";
65442
- if (options.nativeContextObserved) {
66078
+ validatePrivateSkillNativeAuthorityTransition(
66079
+ previous,
66080
+ draft,
66081
+ options.nativeAuthorityTransition
66082
+ );
66083
+ if (options.nativeAuthorityTransition === "revoke" || options.nativeAuthorityTransition === "regrant") {
66084
+ if (canonicalJson(draft.native_binding) !== canonicalJson(previous.native_binding))
66085
+ throw new Error("Private skill native context lineage changed.");
66086
+ } else if (options.nativeContextObserved) {
65443
66087
  if (previous.native_binding && canonicalJson(previous.native_binding) !== canonicalJson(draft.native_binding) || canonicalJson(previous.native_contexts) !== canonicalJson(
65444
66088
  draft.native_contexts.slice(0, previous.native_contexts.length)
65445
66089
  ) || draft.native_contexts.length > previous.native_contexts.length + 1) {
@@ -65507,17 +66151,75 @@ function parsePrivateSkillDestinationCapabilityHold(value) {
65507
66151
  )
65508
66152
  };
65509
66153
  }
65510
- function parseRetainedNativeContexts(value) {
66154
+ function parseRetainedNativeContexts(value, draftId) {
65511
66155
  if (value === void 0) return [];
65512
66156
  if (!Array.isArray(value))
65513
66157
  throw new Error("Private skill native contexts are invalid.");
65514
- const contexts2 = value.map(parsePrivateSkillNativeContext);
66158
+ const contexts2 = value.map(
66159
+ (entry) => parseRetainedPrivateSkillNativeContext(entry, draftId)
66160
+ );
65515
66161
  const sources = new Set(contexts2.map((context) => context.source_digest));
65516
66162
  const contents = new Set(contexts2.map((context) => context.context_digest));
65517
66163
  if (sources.size !== contexts2.length || contents.size !== contexts2.length)
65518
66164
  throw new Error("Private skill native context lineage is duplicated.");
65519
66165
  return contexts2;
65520
66166
  }
66167
+ function parsePrivateSkillNativeAuthorityState(value) {
66168
+ if (!isRecord4(value) || Object.keys(value).sort().join(",") !== "generation,issuance_closed,prepared_events,version" || value.version !== "private-skill-native-authority-state-v1" || !Number.isSafeInteger(value.generation) || Number(value.generation) < 0 || typeof value.issuance_closed !== "boolean" || !Array.isArray(value.prepared_events) || value.prepared_events.length > PRIVATE_SKILL_NATIVE_EVENT_MAX || value.prepared_events.some(
66169
+ (event) => typeof event !== "string" || !/^sha256:[a-f0-9]{64}$/u.test(event)
66170
+ ) || new Set(value.prepared_events).size !== value.prepared_events.length)
66171
+ throw new Error("Private skill native authority state is invalid.");
66172
+ return Object.freeze({
66173
+ version: "private-skill-native-authority-state-v1",
66174
+ generation: Number(value.generation),
66175
+ prepared_events: Object.freeze([...value.prepared_events]),
66176
+ issuance_closed: value.issuance_closed
66177
+ });
66178
+ }
66179
+ function validatePrivateSkillNativeAuthorityTransition(previous, next, transition) {
66180
+ const prior = previous.native_authority_state;
66181
+ const state = next.native_authority_state;
66182
+ const events = prior?.prepared_events ?? [];
66183
+ const nextEvents = state?.prepared_events ?? [];
66184
+ if ((transition === "prepare" || transition === "revoke" || transition === "append") && canonicalJson(nextEvents.slice(0, events.length)) !== canonicalJson(events))
66185
+ throw new Error("Private skill native authority replay history changed.");
66186
+ if (transition === "prepare" || transition === "append") {
66187
+ if (!state || state.issuance_closed || prior?.issuance_closed || state.generation !== (prior?.generation ?? 0))
66188
+ throw new Error("Private skill native authority generation changed.");
66189
+ if (nextEvents.length !== events.length + (transition === "prepare" ? 1 : 0))
66190
+ throw new Error("Private skill native authority replay history changed.");
66191
+ } else if (transition === "revoke") {
66192
+ if (!state || state.generation !== (prior?.generation ?? 0) + 1 || next.native_contexts.length !== previous.native_contexts.length)
66193
+ throw new Error("Private skill native authority revocation is invalid.");
66194
+ if (nextEvents.length < events.length || nextEvents.length > events.length + 1)
66195
+ throw new Error("Private skill native authority replay history changed.");
66196
+ for (let index = 0; index < previous.native_contexts.length; index++) {
66197
+ const before = previous.native_contexts[index];
66198
+ const expected = before.authority ? { ...before, authority: { ...before.authority, revoked: true } } : before;
66199
+ if (canonicalJson(next.native_contexts[index]) !== canonicalJson(expected))
66200
+ throw new Error(
66201
+ "Private skill native authority revocation is invalid."
66202
+ );
66203
+ }
66204
+ } else if (transition === "regrant") {
66205
+ if (!prior || canonicalJson(prior) !== canonicalJson(state) || next.native_contexts.length !== previous.native_contexts.length)
66206
+ throw new Error("Private skill native authority regrant is invalid.");
66207
+ let changed = 0;
66208
+ for (let index = 0; index < previous.native_contexts.length; index++) {
66209
+ const before = previous.native_contexts[index], after = next.native_contexts[index];
66210
+ if (canonicalJson(before) === canonicalJson(after)) continue;
66211
+ if (!before.authority?.revoked || !after.authority || after.authority.revoked || after.authority.generation !== prior.generation || canonicalJson(privateSkillNativeContextProjection(before)) !== canonicalJson(privateSkillNativeContextProjection(after)))
66212
+ throw new Error("Private skill native authority regrant is invalid.");
66213
+ changed++;
66214
+ }
66215
+ if (changed !== 1)
66216
+ throw new Error("Private skill native authority regrant is invalid.");
66217
+ } else if (canonicalJson(prior ?? null) !== canonicalJson(state ?? null)) {
66218
+ throw new Error(
66219
+ "Private skill native authority state changed without a native observation."
66220
+ );
66221
+ }
66222
+ }
65521
66223
  function parsePrivateSkillReformulationAttempts(value, draftId, originalCandidateDigest) {
65522
66224
  if (value === void 0) return [];
65523
66225
  if (!Array.isArray(value) || value.length > PRIVATE_SKILL_REFORMULATION_RECORD_MAX) {
@@ -65912,7 +66614,7 @@ function validatePrivateSkillDestinationTransition(previous, next, allowAudience
65912
66614
  function envelopeMetadata(draft) {
65913
66615
  const recovery = privateSkillRecoveryTransition(draft);
65914
66616
  return {
65915
- version: "private-skill-outbox-envelope-v1",
66617
+ version: draft.native_authority_state ? "private-skill-outbox-envelope-v2" : "private-skill-outbox-envelope-v1",
65916
66618
  draft_id: draft.draft_id,
65917
66619
  state: draft.state,
65918
66620
  candidate_digest: draft.candidate_digest,
@@ -65930,7 +66632,7 @@ function envelopeMetadata(draft) {
65930
66632
  }
65931
66633
  function privateSkillRecoveryTransition(draft, operationalRetryAvailable = false, currentInspectorDigest = PRIVATE_LEARNING_INSPECTOR_DIGEST) {
65932
66634
  const operationalRetryAttempt = operationalRetryAvailable ? privateSkillCurrentEpochOperationalRetryAttempt(draft) : null;
65933
- return derivePrivateSkillRecoveryTransition({
66635
+ const result = derivePrivateSkillRecoveryTransition({
65934
66636
  draft,
65935
66637
  current_inspector_digest: currentInspectorDigest,
65936
66638
  effective_candidate_digest: effectivePrivateSkillCandidateDigest(draft),
@@ -65948,6 +66650,9 @@ function privateSkillRecoveryTransition(draft, operationalRetryAvailable = false
65948
66650
  privateSkillActiveDeliveryLineage(draft)?.possible_delivery_at
65949
66651
  )
65950
66652
  });
66653
+ if (draft.native_authority_state?.issuance_closed && result.next_action?.kind === "capture_native_context")
66654
+ return { ...result, next_action: null };
66655
+ return result;
65951
66656
  }
65952
66657
  function privateSkillCurrentEpochOperationalRetryAttempt(draft) {
65953
66658
  const index = draft.reformulation_attempts.length - 1;
@@ -66000,7 +66705,10 @@ function parseEnvelope2(value) {
66000
66705
  throw new Error("Private skill outbox envelope is invalid.");
66001
66706
  }
66002
66707
  const envelope = parsed;
66003
- if (envelope.version !== "private-skill-outbox-envelope-v1" || envelope.encryption.algorithm !== "aes-256-gcm" || !/^[A-Za-z0-9_-]{16}$/u.test(envelope.encryption.nonce) || !/^[A-Za-z0-9_-]{16,}$/u.test(envelope.encryption.ciphertext) || !/^[A-Za-z0-9_-]{20,32}$/u.test(envelope.encryption.auth_tag)) {
66708
+ if (![
66709
+ "private-skill-outbox-envelope-v1",
66710
+ "private-skill-outbox-envelope-v2"
66711
+ ].includes(envelope.version) || envelope.encryption.algorithm !== "aes-256-gcm" || !/^[A-Za-z0-9_-]{16}$/u.test(envelope.encryption.nonce) || !/^[A-Za-z0-9_-]{16,}$/u.test(envelope.encryption.ciphertext) || !/^[A-Za-z0-9_-]{20,32}$/u.test(envelope.encryption.auth_tag)) {
66004
66712
  throw new Error("Private skill outbox envelope is invalid.");
66005
66713
  }
66006
66714
  assertPrivateSkillDraftId(envelope.draft_id);
@@ -66589,7 +67297,7 @@ async function atomicWritePrivateJson(path, value) {
66589
67297
  }
66590
67298
  await atomicWritePrivateText(path, encoded);
66591
67299
  }
66592
- async function atomicWritePrivateText(path, value) {
67300
+ async function atomicWritePrivateText(path, value, beforePublish) {
66593
67301
  await ensurePrivateDirectory(dirname4(path));
66594
67302
  const temporary = `${path}.${process.pid}.${randomBytes6(8).toString("hex")}.tmp`;
66595
67303
  let handle = null;
@@ -66600,6 +67308,7 @@ async function atomicWritePrivateText(path, value) {
66600
67308
  await handle.close();
66601
67309
  handle = null;
66602
67310
  await chmod3(temporary, 384);
67311
+ beforePublish?.();
66603
67312
  await rename3(temporary, path);
66604
67313
  await chmod3(path, 384);
66605
67314
  } catch (error) {
@@ -67070,7 +67779,8 @@ var LOCAL_ONLY_HANDLERS = Object.freeze({
67070
67779
  ),
67071
67780
  inspect_private_learning_outbox: (payload, context) => inspectPrivateLearningOutbox(
67072
67781
  payload,
67073
- context.persistence
67782
+ context.persistence,
67783
+ context.privateSkillDestination
67074
67784
  ),
67075
67785
  queue_private_skill_import: (payload, context) => context.persistence.queuePrivateSkillHandoff(
67076
67786
  payload,
@@ -67274,7 +67984,8 @@ async function captureLearning(input, persistence, lessonDestination, skillDesti
67274
67984
  link2.draft_id,
67275
67985
  parsed.private_skill,
67276
67986
  link2.context_source,
67277
- ...link2.recovery_context_id ? [link2.recovery_context_id] : []
67987
+ link2.recovery_context_id,
67988
+ skillDestination
67278
67989
  ) : await persistence.queuePrivateSkillCapture(
67279
67990
  parsed.private_skill,
67280
67991
  skillDestination
@@ -67308,7 +68019,7 @@ async function captureLearning(input, persistence, lessonDestination, skillDesti
67308
68019
  ...prepared
67309
68020
  };
67310
68021
  }
67311
- async function inspectPrivateLearningOutbox(input, persistence) {
68022
+ async function inspectPrivateLearningOutbox(input, persistence, destination) {
67312
68023
  const selectedPrivateSkillDraftId = optionalPrivateSkillDraftId(
67313
68024
  input.private_skill_draft_id
67314
68025
  );
@@ -67330,7 +68041,14 @@ async function inspectPrivateLearningOutbox(input, persistence) {
67330
68041
  outbox: publicOutboxSummary(lessonResult.value.summary),
67331
68042
  recovery_items: lessonResult.value.recovery_items
67332
68043
  } : unavailableInspection("private_lesson", lessonResult.reason);
67333
- const selectedDraft = selectedPrivateSkill?.status === "draft" ? privateSkillSelectedDraftResult(selectedPrivateSkill.draft) : selectedPrivateSkill?.status === "submitted" ? privateSkillSelectedSubmittedResult(selectedPrivateSkill.completion) : null;
68044
+ const selectedDraft = selectedPrivateSkill?.status === "draft" ? privateSkillSelectedDraftResult(
68045
+ selectedPrivateSkill.draft,
68046
+ await selectNativeContextForInspection(
68047
+ selectedPrivateSkill.draft,
68048
+ persistence,
68049
+ destination
68050
+ )
68051
+ ) : selectedPrivateSkill?.status === "submitted" ? privateSkillSelectedSubmittedResult(selectedPrivateSkill.completion) : null;
67334
68052
  const selectedDraftError = selectedPrivateSkill?.status === "unavailable" ? privateSkillSelectedDraftError(
67335
68053
  selectedPrivateSkill.draft_id,
67336
68054
  selectedPrivateSkill.error
@@ -67358,6 +68076,36 @@ async function inspectPrivateLearningOutbox(input, persistence) {
67358
68076
  deletion_guidance: "Unsubmitted drafts are retained until an explicit confirmed deletion. Successful content is removed immediately; content-free completion markers expire after 14 days."
67359
68077
  };
67360
68078
  }
68079
+ async function selectNativeContextForInspection(draft, persistence, destination) {
68080
+ const legacyFields = [
68081
+ "context_id",
68082
+ "source_digest",
68083
+ "context_digest",
68084
+ "inspector_digest",
68085
+ "context",
68086
+ "partial"
68087
+ ];
68088
+ const legacyContexts = draft.native_contexts.filter(
68089
+ (context) => Object.keys(context).length === legacyFields.length && legacyFields.every((field) => Object.hasOwn(context, field))
68090
+ );
68091
+ if (legacyContexts.length === draft.native_contexts.length) {
68092
+ return selectPrivateSkillNativeRecoveryContext(draft);
68093
+ }
68094
+ if (destination && persistence.selectPrivateSkillNativeRecoveryContext) {
68095
+ try {
68096
+ return await persistence.selectPrivateSkillNativeRecoveryContext(
68097
+ draft.draft_id,
68098
+ destination
68099
+ );
68100
+ } catch {
68101
+ return null;
68102
+ }
68103
+ }
68104
+ return legacyContexts.length > 0 ? selectPrivateSkillNativeRecoveryContext({
68105
+ ...draft,
68106
+ native_contexts: legacyContexts
68107
+ }) : null;
68108
+ }
67361
68109
  async function inspectSelectedPrivateSkill(draftId, persistence) {
67362
68110
  const before = await readSelectedPrivateSkillCompletion(draftId, persistence);
67363
68111
  if (before) return { status: "submitted", completion: before };
@@ -67667,9 +68415,8 @@ function privateSkillNextAction(draft, _contractVersion) {
67667
68415
  function privateSkillRecoveryContext(draft) {
67668
68416
  return privateSkillReformulationAvailable(draft) ? createPrivateSkillRecoveryContext(draft.candidate) : { status: "context_unavailable" };
67669
68417
  }
67670
- function privateSkillSelectedDraftResult(draft) {
68418
+ function privateSkillSelectedDraftResult(draft, nativeContext) {
67671
68419
  const recoveryContext = privateSkillRecoveryContext(draft);
67672
- const nativeContext = selectPrivateSkillNativeRecoveryContext(draft);
67673
68420
  return {
67674
68421
  ...privateSkillDraftActionResult(draft),
67675
68422
  next_action: privateSkillNextAction(
@@ -67678,8 +68425,22 @@ function privateSkillSelectedDraftResult(draft) {
67678
68425
  ),
67679
68426
  ...privateSkillPermanentRefusalGuidance(draft),
67680
68427
  recovery_context: recoveryContext,
68428
+ ...draft.native_authority_state?.issuance_closed ? {
68429
+ native_context_authority_hold: {
68430
+ reason_code: "native_context_authority_history_capacity",
68431
+ retained_locally: true,
68432
+ new_context_issuance_available: false,
68433
+ instruction: "The retained draft reached its authority-history storage bound. Preserve the draft and spent attempts. Use only recovery context or normal lifecycle actions already available; repeated source selection, another session, or a generated replacement cannot reopen issuance. Never reset history or delete the unresolved draft automatically."
68434
+ }
68435
+ } : {},
67681
68436
  native_recovery_context: nativeContext ? {
67682
- ...nativeContext,
68437
+ // Stored authority and provenance remain inside the protected outbox.
68438
+ context_id: nativeContext.context_id,
68439
+ source_digest: nativeContext.source_digest,
68440
+ context_digest: nativeContext.context_digest,
68441
+ inspector_digest: nativeContext.inspector_digest,
68442
+ context: nativeContext.context,
68443
+ partial: nativeContext.partial,
67683
68444
  authoritative: false,
67684
68445
  is_submission_content: false,
67685
68446
  agent_requirement: "Use this independently inspected native task context only if it adds material task information. Author a complete replacement, not a copy of this partial context. Selecting its ID consumes one new context epoch; generated text alone never resets attempts."
@@ -67773,7 +68534,7 @@ function publicOutboxSummary(summary) {
67773
68534
  }
67774
68535
 
67775
68536
  // ../codex-plugin/scripts/feedback-disposition.mjs
67776
- import { createHash as createHash4, randomBytes as randomBytes7 } from "node:crypto";
68537
+ import { createHash as createHash5, randomBytes as randomBytes7 } from "node:crypto";
67777
68538
  import {
67778
68539
  chmodSync,
67779
68540
  closeSync as closeSync3,
@@ -67837,7 +68598,7 @@ function validIdentifier(value) {
67837
68598
  }
67838
68599
  function exactEventDigest(input) {
67839
68600
  const fields2 = [input.tool, input.query_id, input.result_id ?? ""];
67840
- const hash = createHash4("sha256");
68601
+ const hash = createHash5("sha256");
67841
68602
  for (const field of fields2) {
67842
68603
  const bytes = Buffer.from(field, "utf8");
67843
68604
  hash.update(String(bytes.length), "utf8");
@@ -67850,7 +68611,7 @@ function exactEventDigest(input) {
67850
68611
  function localUsageOwnerId2() {
67851
68612
  const uid = currentUserId2();
67852
68613
  if (uid !== null) return `uid-${uid}`;
67853
- return `home-${createHash4("sha256").update(homedir4()).digest("hex").slice(0, 16)}`;
68614
+ return `home-${createHash5("sha256").update(homedir4()).digest("hex").slice(0, 16)}`;
67854
68615
  }
67855
68616
  function currentUserId2() {
67856
68617
  try {
@@ -67970,10 +68731,10 @@ function cleanupExpiredMarkers(directory, now) {
67970
68731
  visited += 1;
67971
68732
  if (!entry.isFile() || !MARKER_NAME_PATTERN.test(entry.name)) continue;
67972
68733
  markerCount += 1;
67973
- const digest2 = entry.name.slice(0, -".json".length);
68734
+ const digest3 = entry.name.slice(0, -".json".length);
67974
68735
  const path = join5(directory, entry.name);
67975
68736
  try {
67976
- if (removeExpiredMarker(path, readMarker(path, digest2), now)) {
68737
+ if (removeExpiredMarker(path, readMarker(path, digest3), now)) {
67977
68738
  markerCount -= 1;
67978
68739
  }
67979
68740
  } catch {
@@ -68025,7 +68786,7 @@ function acknowledgeFeedbackDenial(input, env = process.env) {
68025
68786
  if (!normalized2) {
68026
68787
  throw new TypeError("Invalid feedback denial acknowledgement input.");
68027
68788
  }
68028
- const digest2 = exactEventDigest(normalized2);
68789
+ const digest3 = exactEventDigest(normalized2);
68029
68790
  const directory = markerDirectory(env);
68030
68791
  const path = markerPath(normalized2, env);
68031
68792
  const now = Date.now();
@@ -68034,7 +68795,7 @@ function acknowledgeFeedbackDenial(input, env = process.env) {
68034
68795
  ensurePrivateDirectory2(directory);
68035
68796
  cleanupExpiredMarkers(directory, now);
68036
68797
  try {
68037
- const existing = readMarker(path, digest2);
68798
+ const existing = readMarker(path, digest3);
68038
68799
  if (Date.parse(existing.expires_at) > now) {
68039
68800
  return {
68040
68801
  status: "acknowledged_host_denial",
@@ -68055,11 +68816,11 @@ function acknowledgeFeedbackDenial(input, env = process.env) {
68055
68816
  ).toISOString();
68056
68817
  writeMarkerAtomically(path, {
68057
68818
  version: FEEDBACK_DENIAL_VERSION,
68058
- event_digest: `sha256:${digest2}`,
68819
+ event_digest: `sha256:${digest3}`,
68059
68820
  acknowledged_at: acknowledgedAt,
68060
68821
  expires_at: expiresAt
68061
68822
  });
68062
- const persisted = readMarker(path, digest2);
68823
+ const persisted = readMarker(path, digest3);
68063
68824
  if (Date.parse(persisted.expires_at) <= now) {
68064
68825
  throw new Error("Local acknowledgement expired before persistence.");
68065
68826
  }
@@ -68163,11 +68924,17 @@ function createLocalPersistenceCapabilities(dependencies = {}) {
68163
68924
  ...await withEncryption(),
68164
68925
  ...destination ? { destination } : {}
68165
68926
  }),
68166
- queuePrivateSkillReformulation: async (draftId, candidate, contextSource, recoveryContextId) => queuePrivateSkillReformulation(draftId, candidate, contextSource, {
68927
+ queuePrivateSkillReformulation: async (draftId, candidate, contextSource, recoveryContextId, destination) => queuePrivateSkillReformulation(draftId, candidate, contextSource, {
68167
68928
  ...await withEncryption(),
68168
- recoveryContextId
68929
+ recoveryContextId,
68930
+ ...destination ? { destination } : {}
68169
68931
  }),
68170
68932
  readPrivateSkillDraft: async (draftId) => refreshPrivateSkillDraft(draftId, await withReadOnlyEncryption()),
68933
+ selectPrivateSkillNativeRecoveryContext: async (draftId, destination) => readPrivateSkillNativeRecoveryContext(
68934
+ draftId,
68935
+ destination,
68936
+ await withReadOnlyEncryption()
68937
+ ),
68171
68938
  readPrivateSkillSubmittedRecord: async (draftId) => readPrivateSkillSubmittedRecord(draftId, await withReadOnlyEncryption()),
68172
68939
  inspectPrivateLearningOutboxes: async (limit) => {
68173
68940
  let encryption;
@@ -68313,7 +69080,7 @@ import {
68313
69080
  rmSync as rmSync2,
68314
69081
  writeFileSync as writeFileSync2
68315
69082
  } from "node:fs";
68316
- import { createHash as createHash5, randomBytes as randomBytes8 } from "node:crypto";
69083
+ import { createHash as createHash6, randomBytes as randomBytes8 } from "node:crypto";
68317
69084
  import { isIP } from "node:net";
68318
69085
  import { homedir as homedir9 } from "node:os";
68319
69086
  import { join as join10 } from "node:path";
@@ -69614,7 +70381,7 @@ function apiDestinationStatus(baseUrl, source) {
69614
70381
  return {
69615
70382
  kind: normalized2 === "https://remembrance.dev" ? "remembrance_cloud" : "custom",
69616
70383
  source,
69617
- fingerprint: createHash5("sha256").update(normalized2, "utf8").digest("hex").slice(0, 16)
70384
+ fingerprint: createHash6("sha256").update(normalized2, "utf8").digest("hex").slice(0, 16)
69618
70385
  };
69619
70386
  }
69620
70387
  function missingPluginLifecycleHealth(surface) {
@@ -69763,10 +70530,9 @@ function isRecord9(value) {
69763
70530
  var MAX_NATIVE_EVENT_BYTES = 512 * 1024;
69764
70531
  async function runPrivateSkillNativeContextCli(input = process.stdin, output = process.stdout) {
69765
70532
  try {
69766
- if (/^(0|false|no)$/iu.test(process.env.REMEMBRANCE_AUTO_CONTRIBUTE ?? "")) {
69767
- output.write('{"status":"disabled"}\n');
69768
- return 0;
69769
- }
70533
+ const automationDisabled = /^(0|false|no)$/iu.test(
70534
+ process.env.REMEMBRANCE_AUTO_CONTRIBUTE ?? ""
70535
+ );
69770
70536
  let size = 0;
69771
70537
  const chunks = [];
69772
70538
  for await (const chunk of input) {
@@ -69779,8 +70545,35 @@ async function runPrivateSkillNativeContextCli(input = process.stdin, output = p
69779
70545
  if (!event || typeof event !== "object" || Array.isArray(event))
69780
70546
  throw new Error("native_context_event_invalid");
69781
70547
  const value = event;
69782
- if (typeof value.session_id !== "string" || value.kind !== "user_prompt" && value.kind !== "private_skill_capture")
70548
+ const withdrawalMatch = value.kind === "qualified_user_prompt" && value.producer === "openclaw_reply_dispatch" && typeof value.prompt === "string" ? /^\/remembrance-context-revoke (psd_[A-Za-z0-9_-]{8,96})(?:\r?\n)?$/u.exec(
70549
+ value.prompt
70550
+ ) : null;
70551
+ const withdrawal = withdrawalMatch?.[0] === value.prompt ? withdrawalMatch : null;
70552
+ if (automationDisabled && !withdrawal) {
70553
+ output.write('{"status":"disabled"}\n');
70554
+ return 0;
70555
+ }
70556
+ if (typeof value.session_id !== "string" || ![
70557
+ "user_prompt",
70558
+ "qualified_user_prompt",
70559
+ "private_skill_capture"
70560
+ ].includes(String(value.kind)))
69783
70561
  throw new Error("native_context_event_invalid");
70562
+ if (value.kind === "user_prompt" || value.kind === "qualified_user_prompt" && (value.producer !== "openclaw_reply_dispatch" || typeof value.prompt !== "string" || typeof value.source_event_digest !== "string" || !/^sha256:[a-f0-9]{64}$/u.test(value.source_event_digest))) {
70563
+ output.write(
70564
+ '{"status":"ignored","reason_code":"applicability_unproven"}\n'
70565
+ );
70566
+ return 0;
70567
+ }
70568
+ if (withdrawal) {
70569
+ const result2 = await revokePrivateSkillNativeContextAuthority(
70570
+ withdrawal[1],
70571
+ { sourceEventDigest: value.source_event_digest }
70572
+ );
70573
+ output.write(`${JSON.stringify(result2)}
70574
+ `);
70575
+ return 0;
70576
+ }
69784
70577
  const access = resolveApiAccess();
69785
70578
  if (!access.credential.apiKey || isUnusableCredentialSource(access.credential.source)) {
69786
70579
  output.write(
@@ -69789,11 +70582,21 @@ async function runPrivateSkillNativeContextCli(input = process.stdin, output = p
69789
70582
  return 0;
69790
70583
  }
69791
70584
  const destination = privateSkillDestinationForAccess(access);
69792
- const result = value.kind === "user_prompt" ? value.origin === "user" && typeof value.prompt === "string" ? await capturePrivateSkillNativeContext(
70585
+ const authority = value.kind === "qualified_user_prompt" ? await preparePrivateSkillNativeContextAuthority(
69793
70586
  value.session_id,
69794
70587
  value.prompt,
69795
- destination
69796
- ) : { status: "ignored" } : typeof value.draft_id === "string" && value.original_capture === true ? await bindPrivateSkillNativeContext(
70588
+ destination,
70589
+ null,
70590
+ { sourceEventDigest: value.source_event_digest }
70591
+ ) : null;
70592
+ const result = value.kind === "qualified_user_prompt" ? authority?.status === "authorized" ? await capturePrivateSkillNativeContext(
70593
+ value.session_id,
70594
+ authority.source,
70595
+ destination,
70596
+ {
70597
+ nativeAuthority: authority.capability
70598
+ }
70599
+ ) : { status: "ignored", reason_code: "applicability_unproven" } : typeof value.draft_id === "string" && value.original_capture === true ? await bindPrivateSkillNativeContext(
69797
70600
  value.draft_id,
69798
70601
  value.session_id,
69799
70602
  destination
@@ -69979,7 +70782,7 @@ function isRecord10(value) {
69979
70782
 
69980
70783
  // src/legacy-lesson-destination-recovery.ts
69981
70784
  var CONTRACT_VERSION = "private-lesson-legacy-destination-recovery-v1";
69982
- var DIGEST3 = /^sha256:[a-f0-9]{64}$/u;
70785
+ var DIGEST4 = /^sha256:[a-f0-9]{64}$/u;
69983
70786
  async function legacyLessonDestinationRecovery(draft, destination, request, dependencies) {
69984
70787
  const alreadyRecovered = isRecoveredForDestination(draft, destination);
69985
70788
  if (!ownerAttestedLegacyPrivateLessonRecoveryEligible(draft) && !alreadyRecovered) {
@@ -69994,7 +70797,7 @@ async function legacyLessonDestinationRecovery(draft, destination, request, depe
69994
70797
  let audience;
69995
70798
  try {
69996
70799
  audience = await dependencies.verifiedOrganizationAudience();
69997
- if (!DIGEST3.test(audience)) throw new Error("Invalid verified audience.");
70800
+ if (!DIGEST4.test(audience)) throw new Error("Invalid verified audience.");
69998
70801
  } catch {
69999
70802
  return refused(draft, "private_lesson_destination_recovery_policy_unavailable");
70000
70803
  }
@@ -70085,7 +70888,7 @@ function isRecoveredForDestination(draft, destination) {
70085
70888
  return draft.attested_organization_audience_hash !== void 0 && draft.destination_binding !== null && canonicalJson(draft.destination_binding) === canonicalJson(destination) && draft.last_error_code !== "private_lesson_destination_attestation_mismatch" && draft.state !== "submitted" && draft.state !== "superseded_redactor";
70086
70889
  }
70087
70890
  function validApproval(request) {
70088
- return request.owner_attested_single_organization === true && request.all_outbox_readers_updated === true && DIGEST3.test(request.review_id) && DIGEST3.test(request.expected_payload_digest) && DIGEST3.test(request.owner_attestation_sha256) && DIGEST3.test(request.organization_audience_hash);
70891
+ return request.owner_attested_single_organization === true && request.all_outbox_readers_updated === true && DIGEST4.test(request.review_id) && DIGEST4.test(request.expected_payload_digest) && DIGEST4.test(request.owner_attestation_sha256) && DIGEST4.test(request.organization_audience_hash);
70089
70892
  }
70090
70893
  function recoveryPlan(draft, destination, audience) {
70091
70894
  const fields2 = {
@@ -70155,7 +70958,7 @@ function inspectPrivateLearningOutbox2(input, dependencies = {}) {
70155
70958
  }
70156
70959
  var MAX_REMOTE_RESPONSE_BYTES = 4 * 1024 * 1024;
70157
70960
  var DOCTOR_PROBE_TIMEOUT_MS = 7500;
70158
- var SERVER_VERSION = true ? "0.2.8" : "0.0.0-dev";
70961
+ var SERVER_VERSION = true ? "0.2.10" : "0.0.0-dev";
70159
70962
  var tools2 = toolDefinitions;
70160
70963
  var doctorCliRequested = process.argv[2] === "doctor";
70161
70964
  var nativeContextCliRequested = process.argv[2] === "--native-context";
@@ -70190,7 +70993,7 @@ var PRINCIPAL_SESSION_AWAITED_TOOLS = /* @__PURE__ */ new Set([
70190
70993
  "report_task_outcome"
70191
70994
  ]);
70192
70995
  function apiAccessKey(access) {
70193
- return createHash6("sha256").update(
70996
+ return createHash7("sha256").update(
70194
70997
  [
70195
70998
  access.configuration.baseUrl,
70196
70999
  access.credential.source,
@@ -72376,8 +73179,8 @@ async function fetchVerifiedPrivateLessonPolicy(access, transport, requiredProfi
72376
73179
  access,
72377
73180
  transport
72378
73181
  );
72379
- const digest2 = privateLessonPolicyDigest(verified.payload);
72380
- if (body.policy_digest !== digest2) {
73182
+ const digest3 = privateLessonPolicyDigest(verified.payload);
73183
+ if (body.policy_digest !== digest3) {
72381
73184
  throw new PrivateLessonPolicySafetyError(
72382
73185
  "Private lesson policy digest does not match its signed payload."
72383
73186
  );
@@ -74159,7 +74962,7 @@ function localRuntimeProfile(identity2) {
74159
74962
  const runtime = isPluginHostSurface(configuredSurface) ? configuredSurface : "other";
74160
74963
  const clientName = connectedClientInfo?.name ?? agentHostBySurface(runtime)?.host_name ?? "MCP";
74161
74964
  const hostSurface = localRuntimeHostSurface(runtime, clientName);
74162
- const profileDigest = createHash6("sha256").update(
74965
+ const profileDigest = createHash7("sha256").update(
74163
74966
  [identity2.key_id, runtime, hostSurface, clientName.toLowerCase()].join(
74164
74967
  ":"
74165
74968
  ),