@remembrance-ai/mcp-server 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -120,14 +120,14 @@ function principalSessionResponseError(status, body, stage) {
120
120
  );
121
121
  }
122
122
  function withPrincipalSessionProbe(report, result) {
123
- const diagnostic = result.error instanceof PrincipalSessionError ? result.error.diagnostic() : new PrincipalSessionError("session_unavailable", "local").diagnostic();
123
+ const diagnostic2 = result.error instanceof PrincipalSessionError ? result.error.diagnostic() : new PrincipalSessionError("session_unavailable", "local").diagnostic();
124
124
  return {
125
125
  ...report,
126
126
  status: !result.ready && report.status === "healthy" ? "attention" : report.status,
127
127
  principal_session: result.ready ? { status: "ready", reason_code: null, remediation: null } : {
128
128
  status: "unavailable",
129
- reason_code: diagnostic.reason_code,
130
- remediation: diagnostic.remediation
129
+ reason_code: diagnostic2.reason_code,
130
+ remediation: diagnostic2.remediation
131
131
  },
132
132
  checks: [
133
133
  ...report.checks,
@@ -135,10 +135,10 @@ function withPrincipalSessionProbe(report, result) {
135
135
  id: "principal_session",
136
136
  status: result.ready ? "pass" : "warning",
137
137
  summary: result.ready ? "The registry verified the installation session used for persistent preferences." : "Signing is configured, but the registry could not verify an installation session. Preferences were not saved by this probe.",
138
- issue_codes: result.ready ? [] : [diagnostic.reason_code],
138
+ issue_codes: result.ready ? [] : [diagnostic2.reason_code],
139
139
  remediation: result.ready ? null : {
140
- code: diagnostic.reason_code,
141
- action: diagnostic.remediation,
140
+ code: diagnostic2.reason_code,
141
+ action: diagnostic2.remediation,
142
142
  automatic: false
143
143
  }
144
144
  }
@@ -4147,23 +4147,23 @@ var ZodEffects = class extends ZodType {
4147
4147
  }
4148
4148
  if (effect.type === "transform") {
4149
4149
  if (ctx.common.async === false) {
4150
- const base = this._def.schema._parseSync({
4150
+ const base2 = this._def.schema._parseSync({
4151
4151
  data: ctx.data,
4152
4152
  path: ctx.path,
4153
4153
  parent: ctx
4154
4154
  });
4155
- if (!isValid(base))
4155
+ if (!isValid(base2))
4156
4156
  return INVALID;
4157
- const result = effect.transform(base.value, checkCtx);
4157
+ const result = effect.transform(base2.value, checkCtx);
4158
4158
  if (result instanceof Promise) {
4159
4159
  throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
4160
4160
  }
4161
4161
  return { status: status.value, value: result };
4162
4162
  } else {
4163
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
4164
- if (!isValid(base))
4163
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base2) => {
4164
+ if (!isValid(base2))
4165
4165
  return INVALID;
4166
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
4166
+ return Promise.resolve(effect.transform(base2.value, checkCtx)).then((result) => ({
4167
4167
  status: status.value,
4168
4168
  value: result
4169
4169
  }));
@@ -7924,12 +7924,12 @@ var PrivateLessonLengthLimitError = class extends Error {
7924
7924
  tool;
7925
7925
  issues;
7926
7926
  diagnostic() {
7927
- const base = this.tool === "capture_learning" ? "$.lesson" : "$";
7927
+ const base2 = this.tool === "capture_learning" ? "$.lesson" : "$";
7928
7928
  return {
7929
7929
  code: "private_lesson_too_long",
7930
7930
  measured_after: "local_redaction",
7931
7931
  issues: this.issues.map(({ field, unit, length, limit }) => ({
7932
- field: field === null ? base : `${base}.${field}`,
7932
+ field: field === null ? base2 : `${base2}.${field}`,
7933
7933
  unit,
7934
7934
  length,
7935
7935
  limit
@@ -8732,6 +8732,9 @@ function privateSkillDestinationBodyLimit(status, body, bodyLength) {
8732
8732
  }
8733
8733
  var captureLearningInputSchema = external_exports.object({
8734
8734
  contract_version: external_exports.literal(PRIVATE_LEARNING_CAPTURE_VERSION).default(PRIVATE_LEARNING_CAPTURE_VERSION),
8735
+ capture_id: external_exports.string().regex(/^cap_[a-f0-9]{32}$/u).optional().describe(
8736
+ "Optional opaque lesson capture identity: cap_ followed by 32 random lowercase hexadecimal characters. Allocate before the first lesson call and reuse with the identical lesson after a lost response. Inspect it locally to reconcile first. A different lesson or destination is refused for the same identity. Supported only with lesson; it grants no submission approval."
8737
+ ),
8735
8738
  lesson: privateLessonPreparationInputSchema.optional(),
8736
8739
  private_skill: privateSkillCaptureSchema.optional(),
8737
8740
  replacement_of: external_exports.union([
@@ -8759,6 +8762,20 @@ var captureLearningInputSchema = external_exports.object({
8759
8762
  path: ["replacement_of"]
8760
8763
  });
8761
8764
  }
8765
+ if (value.capture_id !== void 0 && value.lesson === void 0) {
8766
+ ctx.addIssue({
8767
+ code: external_exports.ZodIssueCode.custom,
8768
+ message: "capture_id is valid only with a lesson payload.",
8769
+ path: ["capture_id"]
8770
+ });
8771
+ }
8772
+ if (value.capture_id !== void 0 && value.replacement_of !== void 0) {
8773
+ ctx.addIssue({
8774
+ code: external_exports.ZodIssueCode.custom,
8775
+ message: "A replacement uses its existing replacement_of identity; omit capture_id.",
8776
+ path: ["capture_id"]
8777
+ });
8778
+ }
8762
8779
  });
8763
8780
  var categoricalAgentFeedbackRequestBaseSchema = agentFeedbackRequestBaseSchema.omit({ lesson: true }).strict();
8764
8781
  var categoricalAgentFeedbackRequestSchema = categoricalAgentFeedbackRequestBaseSchema.superRefine((value, ctx) => {
@@ -9327,11 +9344,11 @@ function rsaPrivateExponentRecoversFactorUncached(modulus, exponent, privateExpo
9327
9344
  oddPart >>= 1n;
9328
9345
  powersOfTwo += 1;
9329
9346
  }
9330
- for (const base of RSA_EXPONENT_FACTOR_WITNESSES) {
9331
- if (base >= modulus) continue;
9332
- const direct = greatestCommonDivisor(base, modulus, metrics);
9347
+ for (const base2 of RSA_EXPONENT_FACTOR_WITNESSES) {
9348
+ if (base2 >= modulus) continue;
9349
+ const direct = greatestCommonDivisor(base2, modulus, metrics);
9333
9350
  if (direct > 1n && direct < modulus) return true;
9334
- let value = modularPower(base, oddPart, modulus, metrics);
9351
+ let value = modularPower(base2, oddPart, modulus, metrics);
9335
9352
  if (value === 1n || value === modulus - 1n) continue;
9336
9353
  for (let round = 1; round <= powersOfTwo; round += 1) {
9337
9354
  metrics.ownershipSteps += 1;
@@ -9361,9 +9378,9 @@ function greatestCommonDivisor(left, right, metrics) {
9361
9378
  }
9362
9379
  return a;
9363
9380
  }
9364
- function modularPower(base, exponent, modulus, metrics) {
9381
+ function modularPower(base2, exponent, modulus, metrics) {
9365
9382
  let result = 1n;
9366
- let factor = base % modulus;
9383
+ let factor = base2 % modulus;
9367
9384
  let remaining = exponent;
9368
9385
  while (remaining > 0n) {
9369
9386
  metrics.ownershipSteps += 1;
@@ -18744,10 +18761,10 @@ function recoveredRsaPrime({ modulus, exponent, privateExponent }, metrics, atte
18744
18761
  powersOfTwo += 1;
18745
18762
  }
18746
18763
  const meter = rsaArithmeticMeter(metrics, modulus);
18747
- for (const base of RSA_FACTOR_SEARCH_BASES) {
18764
+ for (const base2 of RSA_FACTOR_SEARCH_BASES) {
18748
18765
  if (metrics.rsaCrtContinuationProofAttempts >= attempts) return null;
18749
18766
  metrics.rsaCrtContinuationProofAttempts += 1;
18750
- let value = modularPower(base, oddPart, modulus, meter);
18767
+ let value = modularPower(base2, oddPart, modulus, meter);
18751
18768
  for (let round = 0; round < powersOfTwo && value !== 1n && value !== modulus - 1n; round += 1) {
18752
18769
  meter.ownershipSteps += 1;
18753
18770
  const squared = value * value % modulus;
@@ -20823,14 +20840,14 @@ function isShortPemBoundaryFragment(value) {
20823
20840
  return trimmed.length <= 32 && /^-{5}(?:BEGIN|END)[A-Z0-9_-]{0,18}$/iu.test(trimmed) && exactPrivateKeyMarker2(trimmed) === null;
20824
20841
  }
20825
20842
  function uniqueRedactedObjectKey(reserved, used, nextSuffixByBase, candidate) {
20826
- const base = candidate === "[redacted]" ? "[redacted-key]" : candidate;
20827
- if (!reserved.has(base) && !used.has(base)) return base;
20828
- let suffix = nextSuffixByBase.get(base) ?? 2;
20829
- while (reserved.has(`${base}-${suffix}`) || used.has(`${base}-${suffix}`)) {
20843
+ const base2 = candidate === "[redacted]" ? "[redacted-key]" : candidate;
20844
+ if (!reserved.has(base2) && !used.has(base2)) return base2;
20845
+ let suffix = nextSuffixByBase.get(base2) ?? 2;
20846
+ while (reserved.has(`${base2}-${suffix}`) || used.has(`${base2}-${suffix}`)) {
20830
20847
  suffix += 1;
20831
20848
  }
20832
- nextSuffixByBase.set(base, suffix + 1);
20833
- return `${base}-${suffix}`;
20849
+ nextSuffixByBase.set(base2, suffix + 1);
20850
+ return `${base2}-${suffix}`;
20834
20851
  }
20835
20852
  function createRedactionWorkMetrics() {
20836
20853
  return {
@@ -27282,13 +27299,13 @@ function toolArgumentSchemaLocation(schema, path) {
27282
27299
  const child = schemaObject(properties[segment]);
27283
27300
  if (child) {
27284
27301
  name = Object.keys(properties).find((key) => key === segment);
27285
- next.push(child);
27302
+ if (!next.includes(child)) next.push(child);
27286
27303
  }
27287
27304
  } else if (typeof segment === "number") {
27288
27305
  const child = schemaObject(current.items);
27289
27306
  if (child) {
27290
27307
  name = "[]";
27291
- next.push(child);
27308
+ if (!next.includes(child)) next.push(child);
27292
27309
  }
27293
27310
  }
27294
27311
  }
@@ -28349,19 +28366,19 @@ function parseNullableDef(def, refs) {
28349
28366
  };
28350
28367
  }
28351
28368
  if (refs.target === "openApi3") {
28352
- const base2 = parseDef(def.innerType._def, {
28369
+ const base3 = parseDef(def.innerType._def, {
28353
28370
  ...refs,
28354
28371
  currentPath: [...refs.currentPath]
28355
28372
  });
28356
- if (base2 && "$ref" in base2)
28357
- return { allOf: [base2], nullable: true };
28358
- return base2 && { ...base2, nullable: true };
28373
+ if (base3 && "$ref" in base3)
28374
+ return { allOf: [base3], nullable: true };
28375
+ return base3 && { ...base3, nullable: true };
28359
28376
  }
28360
- const base = parseDef(def.innerType._def, {
28377
+ const base2 = parseDef(def.innerType._def, {
28361
28378
  ...refs,
28362
28379
  currentPath: [...refs.currentPath, "anyOf", "0"]
28363
28380
  });
28364
- return base && { anyOf: [base, { type: "null" }] };
28381
+ return base2 && { anyOf: [base2, { type: "null" }] };
28365
28382
  }
28366
28383
 
28367
28384
  // ../../node_modules/zod-to-json-schema/dist/esm/parsers/number.js
@@ -29143,16 +29160,48 @@ var privateLessonDraftReferenceSchema = external_exports.object({
29143
29160
  }).strict();
29144
29161
  var privateLessonInspectSchema = external_exports.object({
29145
29162
  draft_id: external_exports.string().regex(/^pld_[A-Za-z0-9_-]{8,96}$/).optional(),
29163
+ capture_id: external_exports.string().regex(/^cap_[a-f0-9]{32}$/u).optional().describe(
29164
+ "Reconcile one lesson capture by its opaque capture_id without replaying lesson content. Omit draft_id when selecting capture_id."
29165
+ ),
29146
29166
  limit: external_exports.number().int().min(1).max(200).default(50),
29147
29167
  offset: external_exports.number().int().min(0).max(Number.MAX_SAFE_INTEGER - 200).default(0).describe(
29148
29168
  "Zero-based local page offset. Follow next_offset until truncated is false."
29149
29169
  )
29150
- }).strict();
29170
+ }).strict().superRefine((value, ctx) => {
29171
+ if (value.capture_id !== void 0 && value.draft_id !== void 0) {
29172
+ ctx.addIssue({
29173
+ code: external_exports.ZodIssueCode.custom,
29174
+ message: "Select either capture_id or draft_id, not both.",
29175
+ path: ["capture_id"]
29176
+ });
29177
+ }
29178
+ });
29151
29179
  var privateLessonRetrySchema = privateLessonDraftReferenceSchema.extend({
29152
29180
  deliver_rechecked_hold: external_exports.literal(true).optional().describe(
29153
29181
  "Only after the user chose to deliver a held draft whose safety_recheck is passes_current_rule: send it under the current safety rule. A draft the current check still holds is refused locally and not sent."
29182
+ ),
29183
+ legacy_destination_recovery: external_exports.discriminatedUnion("action", [
29184
+ external_exports.object({ action: external_exports.literal("review") }).strict(),
29185
+ external_exports.object({
29186
+ action: external_exports.literal("approve"),
29187
+ review_id: external_exports.string().regex(/^sha256:[a-f0-9]{64}$/),
29188
+ expected_payload_digest: external_exports.string().regex(/^sha256:[a-f0-9]{64}$/),
29189
+ expected_destination: external_exports.object({
29190
+ api_base_sha256: external_exports.string().regex(/^sha256:[a-f0-9]{64}$/),
29191
+ credential_sha256: external_exports.string().regex(/^sha256:[a-f0-9]{64}$/)
29192
+ }).strict(),
29193
+ organization_audience_hash: external_exports.string().regex(/^sha256:[a-f0-9]{64}$/),
29194
+ owner_attested_single_organization: external_exports.literal(true),
29195
+ all_outbox_readers_updated: external_exports.literal(true),
29196
+ owner_attestation_sha256: external_exports.string().regex(/^sha256:[a-f0-9]{64}$/)
29197
+ }).strict()
29198
+ ]).optional().describe(
29199
+ "Explicit legacy destination recovery only. review requests a content-free plan using the signed current organization policy; it changes no draft and sends no lesson. approve requires the exact review fields, new explicit owner confirmation that this draft belongs only to that organization and may be delivered there, the SHA-256 hash of that approval, and confirmation every outbox reader is Remembrance 0.2.6 or newer. Existing submission approval is not migration approval. Approval binds the unchanged encrypted draft locally and returns its normal retry; it does not submit it. Never infer the old destination, reveal retained source, or approve on the owner's behalf."
29154
29200
  )
29155
- });
29201
+ }).refine(
29202
+ (value) => !(value.deliver_rechecked_hold && value.legacy_destination_recovery),
29203
+ { message: "Choose safety-hold release or legacy destination recovery, never both." }
29204
+ );
29156
29205
  var privateLessonDeleteSchema = privateLessonDraftReferenceSchema.extend({
29157
29206
  confirm: external_exports.literal(true).describe(
29158
29207
  "Must be true. Deletion is explicit and leaves a content-free tombstone."
@@ -29227,8 +29276,8 @@ var bootstrapAgentIdentitySchema = external_exports.object({
29227
29276
  force_rotate: external_exports.boolean().default(false).describe("Generate and register a new key even when one exists.")
29228
29277
  }).strict();
29229
29278
  function feedbackToolSchemaFor(privateCaptureMode) {
29230
- const base = privateCaptureMode ? categoricalAgentFeedbackRequestBaseSchema : agentFeedbackRequestBaseSchema;
29231
- return base.extend({
29279
+ const base2 = privateCaptureMode ? categoricalAgentFeedbackRequestBaseSchema : agentFeedbackRequestBaseSchema;
29280
+ return base2.extend({
29232
29281
  verified_attestation: external_exports.boolean().default(false).describe(
29233
29282
  "When true, sign the feedback with the local TOFU key. Missing local identity is initialized automatically; bootstrap_agent_identity remains available for preflight or recovery."
29234
29283
  )
@@ -29405,7 +29454,7 @@ var declaredToolDefinitions = [
29405
29454
  ),
29406
29455
  localNetworkTool(
29407
29456
  "retry_private_lesson_candidate",
29408
- "Retry one retained private-lesson draft through the same private_lesson approval lane as submit_private_lesson_candidate. Network access is allowed only for authorization-pending, due transient retry, newly compatible profile, or refreshable policy states, and for a held draft the current local safety check releases once the user chose to deliver it (deliver_rechecked_hold=true); a fresh ready draft is rejected locally. It never falls back to a public or alternate transport.",
29457
+ "Retry one retained private-lesson draft through the same private_lesson approval lane as submit_private_lesson_candidate. Network access is allowed only for authorization-pending, due transient retry, newly compatible profile, or refreshable policy states, and for a held draft the current local safety check releases once the user chose to deliver it (deliver_rechecked_hold=true); a fresh ready draft is rejected locally. A legacy_destination_recovery review explicitly requests a content-free signed-policy review for one eligible unbound draft, without changing or sending it. Only new explicit owner approval of that exact review and all outbox readers at 0.2.6 or newer permits local destination binding; a separate normal retry performs delivery. Never infer migration approval from submission approval. It never falls back to a public or alternate transport.",
29409
29458
  "retry_private_lesson_candidate",
29410
29459
  privateLessonRetrySchema,
29411
29460
  "content_write"
@@ -30117,9 +30166,29 @@ function normalizeBoundedWriteJsonSchema(schema, name) {
30117
30166
  schema["x-remembrance-validation-rules"] = QUERY_FEEDBACK_VALIDATION_RULES;
30118
30167
  }
30119
30168
  if (name === "capture_learning") {
30120
- 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,
30121
30179
  required: [field]
30122
- }));
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
+ ];
30123
30192
  schema.allOf = [
30124
30193
  {
30125
30194
  if: { required: ["replacement_of"] },
@@ -30136,9 +30205,7 @@ function normalizeBoundedWriteJsonSchema(schema, name) {
30136
30205
  }
30137
30206
  }
30138
30207
  ];
30139
- const replacement = schemaProperty(schema, "replacement_of");
30140
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.";
30141
- const [skillLink, lessonLink] = replacement.anyOf;
30142
30209
  schemaProperty(skillLink, "draft_id").description = "Retained encrypted private-skill draft being replaced.";
30143
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.";
30144
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.";
@@ -30183,7 +30250,7 @@ validateServedToolDefinitionSet(
30183
30250
  );
30184
30251
 
30185
30252
  // src/private-lesson-outbox.ts
30186
- import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes4 } from "node:crypto";
30253
+ import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes5 } from "node:crypto";
30187
30254
  import {
30188
30255
  chmod as chmod2,
30189
30256
  link,
@@ -31561,6 +31628,149 @@ function isLoopError(error) {
31561
31628
  return error instanceof Error && "code" in error && error.code === "ELOOP";
31562
31629
  }
31563
31630
 
31631
+ // src/capture-learning-diagnostics.ts
31632
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
31633
+ import { randomBytes as randomBytes4 } from "node:crypto";
31634
+ var contexts = new AsyncLocalStorage2();
31635
+ var failures = /* @__PURE__ */ new WeakMap();
31636
+ var CaptureLearningReplayError = class extends Error {
31637
+ constructor(code) {
31638
+ super(
31639
+ "This capture identity is already bound to a retained local outcome."
31640
+ );
31641
+ this.code = code;
31642
+ this.name = "CaptureLearningReplayError";
31643
+ }
31644
+ code;
31645
+ };
31646
+ async function withCaptureLearningDiagnostics(operation) {
31647
+ if (contexts.getStore()) return operation();
31648
+ const context = {
31649
+ capture_id: `cap_${randomBytes4(16).toString("hex")}`,
31650
+ correlation_id: `capcorr_${randomBytes4(16).toString("hex")}`,
31651
+ failure_stage: "validation",
31652
+ persistence_outcome: "not_persisted"
31653
+ };
31654
+ return contexts.run(context, async () => {
31655
+ try {
31656
+ return await operation();
31657
+ } catch (error) {
31658
+ const failure = error !== null && (typeof error === "object" || typeof error === "function") ? error : new Error("Private learning capture failed.");
31659
+ failures.set(failure, {
31660
+ ...diagnostic(context),
31661
+ ...preparationConstraintDiagnostic(context, error),
31662
+ ...error instanceof CaptureLearningReplayError ? {
31663
+ code: error.code,
31664
+ recovery: context.replacement_of ? "Inspect the original held draft and the selected replacement. Repeat only the exact same lesson and replacement_of through its existing recovery lane; do not create an unrelated capture." : "Inspect the outcome for this capture_id. It must not be reused for a different lesson or destination, and a submitted or explicitly deleted capture is never recreated."
31665
+ } : {}
31666
+ });
31667
+ throw failure;
31668
+ }
31669
+ });
31670
+ }
31671
+ function captureLearningDiagnostic(error) {
31672
+ return error !== null && (typeof error === "object" || typeof error === "function") ? failures.get(error) : void 0;
31673
+ }
31674
+ function captureLearningCurrentDiagnostic() {
31675
+ const context = contexts.getStore();
31676
+ return context ? diagnostic(context) : void 0;
31677
+ }
31678
+ function currentCaptureLearningId() {
31679
+ return contexts.getStore()?.capture_id;
31680
+ }
31681
+ function adoptCaptureLearningId(captureId) {
31682
+ const context = contexts.getStore();
31683
+ if (context && captureId && /^cap_[a-f0-9]{32}$/u.test(captureId)) {
31684
+ context.capture_id = captureId;
31685
+ }
31686
+ }
31687
+ function markCaptureLearningStage(stage) {
31688
+ const context = contexts.getStore();
31689
+ if (context) context.failure_stage = stage;
31690
+ }
31691
+ function markCaptureLearningReplacement(draftId) {
31692
+ const context = contexts.getStore();
31693
+ if (context) context.replacement_of = draftId;
31694
+ }
31695
+ function markCaptureLearningRoute(route) {
31696
+ const context = contexts.getStore();
31697
+ if (context) context.capture_route = route;
31698
+ }
31699
+ function markCaptureLearningPersisting(draftId) {
31700
+ const context = contexts.getStore();
31701
+ if (!context) return;
31702
+ context.failure_stage = "encrypted_persistence";
31703
+ context.persistence_outcome = "unknown";
31704
+ if (draftId) context.reconciliation_draft_id = draftId;
31705
+ }
31706
+ function markCaptureLearningPersisted(draftId) {
31707
+ const context = contexts.getStore();
31708
+ if (!context) return;
31709
+ context.persistence_outcome = "persisted";
31710
+ context.draft_id = draftId;
31711
+ delete context.reconciliation_draft_id;
31712
+ }
31713
+ function markCaptureLearningNotPersisted() {
31714
+ const context = contexts.getStore();
31715
+ if (!context) return;
31716
+ context.persistence_outcome = "not_persisted";
31717
+ delete context.draft_id;
31718
+ delete context.reconciliation_draft_id;
31719
+ }
31720
+ function diagnostic(context) {
31721
+ return {
31722
+ code: `capture_${context.failure_stage}_failed`,
31723
+ ...context.replacement_of ? { replacement_of: context.replacement_of } : { capture_id: context.capture_id },
31724
+ correlation_id: context.correlation_id,
31725
+ failure_stage: context.failure_stage,
31726
+ persistence_outcome: context.persistence_outcome,
31727
+ ...context.capture_route ? { capture_route: context.capture_route } : {},
31728
+ ...context.draft_id ? { draft_id: context.draft_id } : {},
31729
+ ...context.reconciliation_draft_id ? { reconciliation_draft_id: context.reconciliation_draft_id } : context.persistence_outcome === "unknown" && context.capture_route === "private_skill" ? {
31730
+ next_action: {
31731
+ tool: "inspect_private_learning_outbox",
31732
+ arguments: { limit: 50 }
31733
+ }
31734
+ } : {},
31735
+ candidate_sent: false,
31736
+ ...context.draft_id || context.reconciliation_draft_id ? {
31737
+ next_action: {
31738
+ tool: context.capture_route === "private_skill" ? "inspect_private_learning_outbox" : "inspect_private_lesson_outbox",
31739
+ arguments: context.capture_route === "private_skill" ? {
31740
+ limit: 50,
31741
+ private_skill_draft_id: context.draft_id ?? context.reconciliation_draft_id
31742
+ } : {
31743
+ draft_id: context.draft_id ?? context.reconciliation_draft_id
31744
+ }
31745
+ }
31746
+ } : context.replacement_of ? {
31747
+ next_action: {
31748
+ tool: "inspect_private_lesson_outbox",
31749
+ arguments: { draft_id: context.replacement_of }
31750
+ }
31751
+ } : {},
31752
+ recovery: context.replacement_of && context.persistence_outcome !== "persisted" ? "Inspect the original held draft and any retained replacement. Correct a bounded refusal, then repeat only the exact same lesson and replacement_of. This uses the existing deterministic replacement lane; do not add capture_id or create an unrelated capture." : context.persistence_outcome === "persisted" ? "Inspect the retained draft and resume its returned next action. Do not create a replacement capture." : context.persistence_outcome === "not_persisted" ? "No draft was saved by this attempt. Correct the bounded validation or storage issue, then retry; use the same capture_id for a lesson capture." : context.capture_route === "private_lesson" ? "Inspect using capture_id, or repeat the exact same lesson and capture_id. This reconciles the selected local write before any new draft can be created. Do not change the capture_id or payload to bypass an unknown outcome." : "Inspect the private learning outbox before retrying. The outcome is unknown; a new capture may duplicate a retained draft."
31753
+ };
31754
+ }
31755
+ function preparationConstraintDiagnostic(context, error) {
31756
+ if (context.failure_stage !== "preparation" || !(error instanceof ZodError))
31757
+ return {};
31758
+ if (!error.issues.some(
31759
+ (issue) => issue.path[0] === "evidence_hashes" && issue.code === "invalid_string" && issue.validation === "regex"
31760
+ ))
31761
+ return {};
31762
+ return {
31763
+ validation_issues: [
31764
+ {
31765
+ path: "$.lesson.evidence_hashes[]",
31766
+ code: "invalid_string",
31767
+ constraint: "^sha256:[a-f0-9]{64}$"
31768
+ }
31769
+ ],
31770
+ remediation: "Use sha256: followed by exactly 64 lowercase hexadecimal characters; omit evidence_hashes when no digest exists."
31771
+ };
31772
+ }
31773
+
31564
31774
  // src/private-lesson-outbox.ts
31565
31775
  var PRIVATE_LESSON_OUTBOX_VERSION = "private-lesson-outbox-v1";
31566
31776
  var PRIVATE_LESSON_OUTBOX_MAX_BYTES = 64 * 1024 * 1024;
@@ -31666,18 +31876,78 @@ async function releaseRecheckedPrivateLessonHold(draftId, options = {}) {
31666
31876
  });
31667
31877
  }
31668
31878
  async function queuePreparedPrivateLesson(prepared, policy, options = {}) {
31879
+ const draftId = options.captureId ? privateLessonCaptureDraftId(options.captureId) : createPublicId("pld");
31669
31880
  const outbox = await readyOutbox(options);
31670
31881
  const draft = newPrivateLessonDraft(
31671
31882
  prepared,
31672
- createPublicId("pld"),
31883
+ draftId,
31673
31884
  policy,
31674
31885
  options.destination ?? null,
31675
- options.now ?? /* @__PURE__ */ new Date()
31886
+ options.now ?? /* @__PURE__ */ new Date(),
31887
+ options.captureId !== void 0
31676
31888
  );
31677
- await writeDraft(draft, outbox, false);
31678
- return draft;
31889
+ return withPrivateLessonOutboxLock(outbox.directory, async () => {
31890
+ if (options.captureId) {
31891
+ markCaptureLearningPersisting(draftId);
31892
+ const unresolved = await reconcilePrivateLessonTemporaryWrites(
31893
+ outbox.directory,
31894
+ outbox.encryption
31895
+ );
31896
+ if (unresolved.has(draftId)) {
31897
+ throw new CaptureLearningReplayError("capture_reconciliation_required");
31898
+ }
31899
+ if ((await privateLessonQuarantineEntriesForDraft(
31900
+ outbox.directory,
31901
+ draftId
31902
+ )).length > 0) {
31903
+ throw new CaptureLearningReplayError("capture_reconciliation_required");
31904
+ }
31905
+ if (existsSync2(tombstonePath(outbox.directory, draftId))) {
31906
+ throw new CaptureLearningReplayError("capture_id_deleted");
31907
+ }
31908
+ await assertNotReplacedUnlocked(outbox.directory, draftId);
31909
+ const completion = existsSync2(
31910
+ submittedRecordPath(outbox.directory, draftId)
31911
+ ) ? await readPrivateLessonSubmittedRecord(draftId, {
31912
+ ...options,
31913
+ encryption: outbox.encryption,
31914
+ outboxDirectory: outbox.directory
31915
+ }) : null;
31916
+ if (completion) {
31917
+ markCaptureLearningPersisted(draftId);
31918
+ throw new CaptureLearningReplayError("capture_id_already_submitted");
31919
+ }
31920
+ if (existsSync2(draftPath(outbox.directory, draftId))) {
31921
+ const existing = await readPrivateLessonDraft(draftId, {
31922
+ ...options,
31923
+ encryption: outbox.encryption,
31924
+ outboxDirectory: outbox.directory
31925
+ });
31926
+ markCaptureLearningPersisted(draftId);
31927
+ if (existing.payload_digest !== draft.payload_digest || existing.redactor_digest !== draft.redactor_digest) {
31928
+ throw new CaptureLearningReplayError("capture_id_payload_mismatch");
31929
+ }
31930
+ if (canonicalJson(existing.destination_binding) !== canonicalJson(draft.destination_binding)) {
31931
+ throw new CaptureLearningReplayError(
31932
+ "capture_id_destination_mismatch"
31933
+ );
31934
+ }
31935
+ return existing;
31936
+ }
31937
+ markCaptureLearningNotPersisted();
31938
+ }
31939
+ await writeDraft(draft, outbox, false);
31940
+ markCaptureLearningPersisted(draftId);
31941
+ return draft;
31942
+ });
31679
31943
  }
31680
- function newPrivateLessonDraft(prepared, draftId, policy, destination, now) {
31944
+ function privateLessonCaptureDraftId(captureId) {
31945
+ if (!/^cap_[a-f0-9]{32}$/u.test(captureId)) {
31946
+ throw new Error("Private lesson capture identity is invalid.");
31947
+ }
31948
+ return `pld_${hashValue(`private-lesson-capture-v1:${captureId}`).replace(/^sha256:/u, "")}`;
31949
+ }
31950
+ function newPrivateLessonDraft(prepared, draftId, policy, destination, now, stableCaptureIdentity = false) {
31681
31951
  const createdAt = now.toISOString();
31682
31952
  const state = prepared.status === "held_safety" ? "held_safety" : policy ? "ready" : "awaiting_authorization";
31683
31953
  return {
@@ -31693,10 +31963,9 @@ function newPrivateLessonDraft(prepared, draftId, policy, destination, now) {
31693
31963
  policy,
31694
31964
  destination_binding: destination ? parsePrivateLessonDestination(destination) : null,
31695
31965
  idempotency_key: `private-lesson-${hashValue(
31696
- canonicalJson({
31697
- draft_id: draftId,
31698
- payload_digest: prepared.payload_digest
31699
- })
31966
+ canonicalJson(
31967
+ stableCaptureIdentity ? { draft_id: draftId } : { draft_id: draftId, payload_digest: prepared.payload_digest }
31968
+ )
31700
31969
  ).replace(/^sha256:/, "")}`,
31701
31970
  attempts: 0,
31702
31971
  next_retry_at: null,
@@ -31800,6 +32069,14 @@ async function queuePrivateLessonReplacement(replacementOf, prepared, options =
31800
32069
  const attempts = original.replacement_attempts ?? [];
31801
32070
  const digest2 = prepared.payload_digest;
31802
32071
  const draftId = privateLessonReplacementDraftId(replacementOf, digest2);
32072
+ markCaptureLearningPersisting(draftId);
32073
+ const unresolved = await reconcilePrivateLessonTemporaryWrites(
32074
+ directory,
32075
+ outbox.encryption
32076
+ );
32077
+ if (unresolved.has(draftId) || (await privateLessonQuarantineEntriesForDraft(directory, draftId)).length > 0) {
32078
+ throw new CaptureLearningReplayError("capture_reconciliation_required");
32079
+ }
31803
32080
  const replay = attempts.includes(digest2);
31804
32081
  const used = replay ? attempts.length : attempts.length + 1;
31805
32082
  if (!replay && privateLessonCapturedForOtherDestination(original, options.destination)) {
@@ -31830,11 +32107,13 @@ async function queuePrivateLessonReplacement(replacementOf, prepared, options =
31830
32107
  throw refuse("replacement_deleted", used, draftId);
31831
32108
  }
31832
32109
  if (existsSync2(draftPath(directory, draftId))) {
32110
+ const existing = await readPrivateLessonDraft(draftId, {
32111
+ ...read2,
32112
+ encryption: outbox.encryption
32113
+ });
32114
+ markCaptureLearningPersisted(draftId);
31833
32115
  return {
31834
- draft: await readPrivateLessonDraft(draftId, {
31835
- ...read2,
31836
- encryption: outbox.encryption
31837
- }),
32116
+ draft: existing,
31838
32117
  attempts_remaining: PRIVATE_LESSON_REPLACEMENT_MAX_ATTEMPTS - used,
31839
32118
  replayed: true
31840
32119
  };
@@ -31906,10 +32185,15 @@ async function readPrivateLessonDraft(draftId, options = {}) {
31906
32185
  assertDraftId(draftId);
31907
32186
  const outbox = await readyOutbox(options, false);
31908
32187
  return withPrivateLessonOutboxLock(outbox.directory, async () => {
31909
- await reconcilePrivateLessonTemporaryWrites(
32188
+ const unresolved = await reconcilePrivateLessonTemporaryWrites(
31910
32189
  outbox.directory,
31911
32190
  outbox.encryption
31912
32191
  );
32192
+ const unresolvedError = unresolved.get(draftId);
32193
+ if (unresolvedError) throw unresolvedError;
32194
+ if (!existsSync2(draftPath(outbox.directory, draftId)) && (await privateLessonQuarantineEntriesForDraft(outbox.directory, draftId)).length > 0) {
32195
+ throw new PrivateLessonDraftUnavailableError(draftId, "corrupt");
32196
+ }
31913
32197
  if (existsSync2(tombstonePath(outbox.directory, draftId))) {
31914
32198
  throw new PrivateLessonDraftUnavailableError(draftId, "deleted");
31915
32199
  }
@@ -32105,6 +32389,67 @@ async function updatePrivateLessonDraft(draftId, update, options = {}) {
32105
32389
  return next;
32106
32390
  });
32107
32391
  }
32392
+ function ownerAttestedLegacyPrivateLessonRecoveryEligible(draft) {
32393
+ const legacyUnbound = draft.destination_binding === null && draft.last_error_code === "private_lesson_destination_legacy_unbound" && (draft.state === "held_validation" || draft.state === "retry_scheduled");
32394
+ const heldForOtherOrganization = draft.attested_organization_audience_hash !== void 0 && draft.last_error_code === "private_lesson_destination_attestation_mismatch" && draft.state === "held_validation";
32395
+ return (legacyUnbound || heldForOtherOrganization) && draft.policy === null && draft.held_reasons.length === 0 && draft.hold_telemetry_status === "not_required" && draft.hold_event_digest === null && draft.hold_receipt_digest === null && draft.hold_reported_at === null && draft.submitted_at === null && draft.receipt_digest === null && draft.terminal_reason === null;
32396
+ }
32397
+ async function recoverOwnerAttestedLegacyPrivateLessonDestination(input, options = {}) {
32398
+ assertDraftId(input.draft_id);
32399
+ if (input.owner_attested_single_organization !== true || !isSha256Digest(input.expected_payload_digest) || !isSha256Digest(input.organization_audience_hash) || !isSha256Digest(input.owner_attestation_sha256) || input.dry_run !== void 0 && typeof input.dry_run !== "boolean") {
32400
+ throw new Error("Explicit owner-attested legacy recovery authorization is required.");
32401
+ }
32402
+ const destination = parsePrivateLessonDestination(input.destination);
32403
+ const outbox = await readyOutbox(options, false);
32404
+ return withPrivateLessonOutboxLock(outbox.directory, async () => {
32405
+ if (existsSync2(tombstonePath(outbox.directory, input.draft_id)) || existsSync2(submittedRecordPath(outbox.directory, input.draft_id))) {
32406
+ throw new Error("Legacy recovery requires an unresolved retained draft.");
32407
+ }
32408
+ const path = draftPath(outbox.directory, input.draft_id);
32409
+ await assertRegularPrivateFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES);
32410
+ const serialized = await readBoundedFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES);
32411
+ const envelope = parseEnvelope(serialized, input.draft_id);
32412
+ const current = await decryptDraft(envelope, outbox.encryption);
32413
+ if (!ownerAttestedLegacyPrivateLessonRecoveryEligible(current) || current.payload_digest !== input.expected_payload_digest) {
32414
+ throw new Error("Selected draft does not match the owner-attested legacy recovery scope.");
32415
+ }
32416
+ const now = (options.now ?? /* @__PURE__ */ new Date()).toISOString();
32417
+ const next = {
32418
+ ...current,
32419
+ destination_binding: destination,
32420
+ attested_organization_audience_hash: input.organization_audience_hash,
32421
+ state: "retry_scheduled",
32422
+ next_retry_at: now,
32423
+ last_error_code: null,
32424
+ updated_at: now
32425
+ };
32426
+ const encryption = {
32427
+ key: await readPrivateLessonOutboxKey(outbox.encryption, envelope.encryption.key_source),
32428
+ source: envelope.encryption.key_source
32429
+ };
32430
+ if (!input.dry_run) await writeDraft(next, { ...outbox, encryption }, true);
32431
+ return {
32432
+ draft_id: current.draft_id,
32433
+ payload_digest: current.payload_digest,
32434
+ original_identity_sha256: hashValue(canonicalJson({
32435
+ draft_id: current.draft_id,
32436
+ canonical_payload: current.canonical_payload,
32437
+ payload_digest: current.payload_digest,
32438
+ redaction_version: current.redaction_version,
32439
+ redactor_digest: current.redactor_digest,
32440
+ idempotency_key: current.idempotency_key,
32441
+ policy: current.policy,
32442
+ created_at: current.created_at
32443
+ })),
32444
+ before_envelope_sha256: hashValue(serialized),
32445
+ after_envelope_sha256: input.dry_run ? null : hashValue(await readBoundedFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES)),
32446
+ owner_attestation_sha256: input.owner_attestation_sha256,
32447
+ organization_audience_hash: input.organization_audience_hash,
32448
+ status: input.dry_run ? "destination_recovery_preflight" : "destination_recovered",
32449
+ candidate_sent: false
32450
+ };
32451
+ });
32452
+ }
32108
32453
  async function completePrivateLessonSubmission(draftId, input, options = {}) {
32109
32454
  assertDraftId(draftId);
32110
32455
  const outbox = await readyOutbox(options);
@@ -32631,7 +32976,7 @@ async function inspectPrivateLessonOutboxHealth(options = {}) {
32631
32976
  const env = options.env ?? process.env;
32632
32977
  const directory = options.outboxDirectory ?? privateLessonOutboxDirectory(env, options.homeDirectory);
32633
32978
  let encryption = options.encryption ?? null;
32634
- let diagnostic;
32979
+ let diagnostic2;
32635
32980
  if (!encryption) {
32636
32981
  try {
32637
32982
  encryption = await readExistingPrivateLessonOutboxEncryption(
@@ -32639,21 +32984,21 @@ async function inspectPrivateLessonOutboxHealth(options = {}) {
32639
32984
  options
32640
32985
  );
32641
32986
  } catch (error) {
32642
- diagnostic = error instanceof PrivateOutboxStorageError ? error.diagnostic() : privateOutboxStorageError(error, "fallback_key_read").diagnostic();
32987
+ diagnostic2 = error instanceof PrivateOutboxStorageError ? error.diagnostic() : privateOutboxStorageError(error, "fallback_key_read").diagnostic();
32643
32988
  }
32644
32989
  }
32645
32990
  const inventory = retainedKeyInventory({
32646
32991
  ...options,
32647
32992
  outboxDirectory: directory
32648
32993
  });
32649
- if (!encryption && !diagnostic) {
32650
- diagnostic = privateLearningKeyBootstrapHold(
32994
+ if (!encryption && !diagnostic2) {
32995
+ diagnostic2 = privateLearningKeyBootstrapHold(
32651
32996
  inventory,
32652
32997
  "confirmed_missing",
32653
32998
  "fallback_key_read"
32654
32999
  )?.diagnostic();
32655
33000
  }
32656
- const encryptionReady = diagnostic ? diagnostic.reason_code === "outbox_key_missing" ? false : null : encryption !== null;
33001
+ const encryptionReady = diagnostic2 ? diagnostic2.reason_code === "outbox_key_missing" ? false : null : encryption !== null;
32657
33002
  const keyFileState = () => privateLessonFallbackKeyState(
32658
33003
  { ...options, outboxDirectory: directory },
32659
33004
  encryption?.source,
@@ -32664,8 +33009,8 @@ async function inspectPrivateLessonOutboxHealth(options = {}) {
32664
33009
  return {
32665
33010
  storage_initialized: false,
32666
33011
  encryption_ready: encryptionReady,
32667
- encryption_source: diagnostic ? null : encryption?.source ?? "uninitialized",
32668
- ...diagnostic ? { diagnostic } : {},
33012
+ encryption_source: diagnostic2 ? null : encryption?.source ?? "uninitialized",
33013
+ ...diagnostic2 ? { diagnostic: diagnostic2 } : {},
32669
33014
  ...await keyFileState(),
32670
33015
  total_bytes: 0,
32671
33016
  ceiling_bytes: ceilingBytes2,
@@ -32780,8 +33125,8 @@ async function inspectPrivateLessonOutboxHealth(options = {}) {
32780
33125
  return {
32781
33126
  storage_initialized: true,
32782
33127
  encryption_ready: encryptionReady,
32783
- encryption_source: diagnostic ? null : "uninitialized",
32784
- ...diagnostic ? { diagnostic } : {},
33128
+ encryption_source: diagnostic2 ? null : "uninitialized",
33129
+ ...diagnostic2 ? { diagnostic: diagnostic2 } : {},
32785
33130
  ...keyFile,
32786
33131
  total_bytes: totalBytes,
32787
33132
  ceiling_bytes: ceilingBytes,
@@ -32940,7 +33285,7 @@ async function resolveFallbackOutboxEncryption(options) {
32940
33285
  encoded = await readConcurrentPrivateLessonFallbackKey(path);
32941
33286
  } catch (error) {
32942
33287
  if (!isMissingError2(error)) throw error;
32943
- encoded = randomBytes4(32).toString("base64url");
33288
+ encoded = randomBytes5(32).toString("base64url");
32944
33289
  try {
32945
33290
  await atomicWritePrivate(path, `${encoded}
32946
33291
  `);
@@ -33187,7 +33532,7 @@ async function writeDraftUnlocked(draft, outbox, replace, _currentOutboxBytes, a
33187
33532
  if (plaintext.length > PRIVATE_LESSON_DRAFT_MAX_BYTES) {
33188
33533
  throw new Error("Private lesson draft exceeds its local size limit.");
33189
33534
  }
33190
- const nonce = randomBytes4(12);
33535
+ const nonce = randomBytes5(12);
33191
33536
  const aad = Buffer.from(
33192
33537
  canonicalJson({
33193
33538
  version: "private-lesson-outbox-envelope-v1",
@@ -33245,7 +33590,28 @@ async function writeDraftUnlocked(draft, outbox, replace, _currentOutboxBytes, a
33245
33590
  if (replace) {
33246
33591
  await atomicReplacePrivate(path, serialized);
33247
33592
  } else {
33248
- await atomicCreatePrivateLessonEntry(path, serialized);
33593
+ markCaptureLearningPersisting(validated.draft_id);
33594
+ try {
33595
+ await atomicCreatePrivateLessonEntry(path, serialized);
33596
+ } catch (error) {
33597
+ try {
33598
+ await assertRegularPrivateFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES);
33599
+ const retained = await decryptDraft(
33600
+ parseEnvelope(
33601
+ await readBoundedFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES),
33602
+ validated.draft_id
33603
+ ),
33604
+ outbox.encryption,
33605
+ true
33606
+ );
33607
+ if (retained.payload_digest === validated.payload_digest) {
33608
+ markCaptureLearningPersisted(validated.draft_id);
33609
+ }
33610
+ } catch {
33611
+ }
33612
+ throw error;
33613
+ }
33614
+ markCaptureLearningPersisted(validated.draft_id);
33249
33615
  }
33250
33616
  }
33251
33617
  async function decryptDraft(envelope, encryption, allowUnsupportedProfile = false) {
@@ -33861,13 +34227,13 @@ async function appendPrivateLessonQuarantineRecoveryItems(directory, items) {
33861
34227
  }
33862
34228
  function privateLessonRecoveryItem(draftId, reasonCode, storageError) {
33863
34229
  if (reasonCode === "undecryptable_entry") {
33864
- const diagnostic = storageError?.diagnostic();
34230
+ const diagnostic2 = storageError?.diagnostic();
33865
34231
  return {
33866
34232
  lane: "private_lesson",
33867
34233
  draft_id: draftId,
33868
34234
  reason_code: reasonCode,
33869
- remediation: diagnostic?.remediation ?? "Restore access to the original encryption key, then inspect the retained draft again. Do not delete or regenerate it.",
33870
- ...diagnostic ? { diagnostic } : {}
34235
+ remediation: diagnostic2?.remediation ?? "Restore access to the original encryption key, then inspect the retained draft again. Do not delete or regenerate it.",
34236
+ ...diagnostic2 ? { diagnostic: diagnostic2 } : {}
33871
34237
  };
33872
34238
  }
33873
34239
  if (reasonCode === "held_safety_recovery_required") {
@@ -33899,6 +34265,7 @@ function privateLessonRecoveryItem(draftId, reasonCode, storageError) {
33899
34265
  };
33900
34266
  }
33901
34267
  async function reconcilePrivateLessonTemporaryWrites(directory, encryption) {
34268
+ const unresolved = /* @__PURE__ */ new Map();
33902
34269
  const groups = /* @__PURE__ */ new Map();
33903
34270
  for (const entry of await readdir(directory, { withFileTypes: true })) {
33904
34271
  if (/^\.[a-f0-9]{24}\.(?:capacity|replaced)\.tmp$/u.test(entry.name) && entry.isFile()) {
@@ -33919,9 +34286,15 @@ async function reconcilePrivateLessonTemporaryWrites(directory, encryption) {
33919
34286
  const envelope = parseEnvelope(value, draftId);
33920
34287
  await decryptDraft(envelope, encryption, true);
33921
34288
  } catch (error) {
33922
- if (isPrivateOutboxKeyAccessError(error)) continue;
34289
+ if (isPrivateOutboxKeyAccessError(error)) {
34290
+ if (draftId) unresolved.set(draftId, error);
34291
+ continue;
34292
+ }
33923
34293
  if (error instanceof PrivateOutboxStorageError) throw error;
33924
- if (error instanceof PrivateOutboxDecryptionError) continue;
34294
+ if (error instanceof PrivateOutboxDecryptionError) {
34295
+ if (draftId) unresolved.set(draftId, error);
34296
+ continue;
34297
+ }
33925
34298
  const recoveryId = derivedPrivateLessonRecoveryId(entry.name);
33926
34299
  await quarantinePrivateLessonTemporary(
33927
34300
  directory,
@@ -33975,6 +34348,11 @@ async function reconcilePrivateLessonTemporaryWrites(directory, encryption) {
33975
34348
  await unlink2(join3(directory, duplicate.name));
33976
34349
  }
33977
34350
  } else {
34351
+ const draftId = target.slice(0, -".lesson.json".length);
34352
+ unresolved.set(
34353
+ draftId,
34354
+ new PrivateLessonDraftUnavailableError(draftId, "corrupt")
34355
+ );
33978
34356
  for (const temporary of temporaryValues) {
33979
34357
  await quarantinePrivateLessonTemporary(
33980
34358
  directory,
@@ -33985,6 +34363,7 @@ async function reconcilePrivateLessonTemporaryWrites(directory, encryption) {
33985
34363
  }
33986
34364
  }
33987
34365
  }
34366
+ return unresolved;
33988
34367
  }
33989
34368
  async function validatePrivateLessonCanonicalPath(path, name, encryption) {
33990
34369
  const draftId = name.match(/^(pld_[A-Za-z0-9_-]{8,96})/u)?.[1];
@@ -34046,7 +34425,7 @@ async function quarantinePrivateLessonTemporary(directory, draftId, temporaryNam
34046
34425
  join3(directory, temporaryName),
34047
34426
  join3(
34048
34427
  quarantine,
34049
- `${draftId}.${reason}.${randomBytes4(8).toString("hex")}.retained`
34428
+ `${draftId}.${reason}.${randomBytes5(8).toString("hex")}.retained`
34050
34429
  )
34051
34430
  );
34052
34431
  }
@@ -34092,7 +34471,7 @@ async function recordPrivateLessonCapacityRejection(directory, rejectedCaptureBy
34092
34471
  const path = join3(directory, PRIVATE_LESSON_CAPACITY_STATE_FILE);
34093
34472
  const temporary = join3(
34094
34473
  directory,
34095
- `.${randomBytes4(12).toString("hex")}.capacity.tmp`
34474
+ `.${randomBytes5(12).toString("hex")}.capacity.tmp`
34096
34475
  );
34097
34476
  const encoded = `${canonicalJson({
34098
34477
  version: "private-outbox-capacity-v1",
@@ -34178,7 +34557,7 @@ async function atomicWritePrivate(path, data) {
34178
34557
  async function atomicCreatePrivateLessonEntry(path, data, temporarySuffix = ".tmp") {
34179
34558
  const temporary = join3(
34180
34559
  dirname3(path),
34181
- `.${randomBytes4(12).toString("hex")}${temporarySuffix}`
34560
+ `.${randomBytes5(12).toString("hex")}${temporarySuffix}`
34182
34561
  );
34183
34562
  try {
34184
34563
  await atomicWritePrivate(temporary, data);
@@ -34194,7 +34573,7 @@ async function atomicReplacePrivate(path, data) {
34194
34573
  await assertRegularPrivateFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES);
34195
34574
  const temporary = join3(
34196
34575
  dirname3(path),
34197
- `.${randomBytes4(12).toString("hex")}.tmp`
34576
+ `.${randomBytes5(12).toString("hex")}.tmp`
34198
34577
  );
34199
34578
  try {
34200
34579
  await atomicWritePrivate(temporary, data);
@@ -34989,18 +35368,18 @@ var require_commonmark = __commonJS({
34989
35368
  strIdx += 1;
34990
35369
  if (str.charCodeAt(strIdx) === 35) {
34991
35370
  var start = strIdx + 1;
34992
- var base = 10;
35371
+ var base2 = 10;
34993
35372
  var cp = str.charCodeAt(start);
34994
35373
  if ((cp | 32) === 120) {
34995
- base = 16;
35374
+ base2 = 16;
34996
35375
  strIdx += 1;
34997
35376
  start += 1;
34998
35377
  }
34999
- while ((cp = str.charCodeAt(++strIdx)) >= 48 && cp <= 57 || base === 16 && (cp | 32) >= 97 && (cp | 32) <= 102)
35378
+ while ((cp = str.charCodeAt(++strIdx)) >= 48 && cp <= 57 || base2 === 16 && (cp | 32) >= 97 && (cp | 32) <= 102)
35000
35379
  ;
35001
35380
  if (start !== strIdx) {
35002
35381
  var entity = str.substring(start, strIdx);
35003
- var parsed = parseInt(entity, base);
35382
+ var parsed = parseInt(entity, base2);
35004
35383
  if (str.charCodeAt(strIdx) === 59) {
35005
35384
  strIdx += 1;
35006
35385
  } else if (strict) {
@@ -54823,15 +55202,15 @@ var Inst = class Inst2 {
54823
55202
  }
54824
55203
  return false;
54825
55204
  }
54826
- let base = 0;
55205
+ let base2 = 0;
54827
55206
  let n = len >> 1;
54828
55207
  while (n > 1) {
54829
55208
  const half = n >> 1;
54830
- base += this.runes[base + half << 1] <= r ? half : 0;
55209
+ base2 += this.runes[base2 + half << 1] <= r ? half : 0;
54831
55210
  n -= half;
54832
55211
  }
54833
- base += this.runes[base << 1] <= r ? 1 : 0;
54834
- const m = base - 1;
55212
+ base2 += this.runes[base2 << 1] <= r ? 1 : 0;
55213
+ const m = base2 - 1;
54835
55214
  return m >= 0 && r <= this.runes[m << 1 | 1];
54836
55215
  }
54837
55216
  matchRunePos(r) {
@@ -54849,15 +55228,15 @@ var Inst = class Inst2 {
54849
55228
  }
54850
55229
  return -1;
54851
55230
  }
54852
- let base = 0;
55231
+ let base2 = 0;
54853
55232
  let n = len >> 1;
54854
55233
  while (n > 1) {
54855
55234
  const half = n >> 1;
54856
- base += this.runes[base + half << 1] <= r ? half : 0;
55235
+ base2 += this.runes[base2 + half << 1] <= r ? half : 0;
54857
55236
  n -= half;
54858
55237
  }
54859
- base += this.runes[base << 1] <= r ? 1 : 0;
54860
- const m = base - 1;
55238
+ base2 += this.runes[base2 << 1] <= r ? 1 : 0;
55239
+ const m = base2 - 1;
54861
55240
  return m >= 0 && r <= this.runes[m << 1 | 1] ? m : -1;
54862
55241
  }
54863
55242
  /**
@@ -62604,7 +62983,7 @@ function inspectPrivateSkillCandidate(candidate) {
62604
62983
  }
62605
62984
 
62606
62985
  // src/private-skill-outbox.ts
62607
- import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes5 } from "node:crypto";
62986
+ import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes6 } from "node:crypto";
62608
62987
  import {
62609
62988
  chmod as chmod3,
62610
62989
  lstat as lstat3,
@@ -64831,7 +65210,7 @@ async function ensurePrivateDirectory(path) {
64831
65210
  async function writePrivateSkillDraft(draft, directory, encryption, env = process.env) {
64832
65211
  const parsed = validatePrivateSkillDraft(draft);
64833
65212
  const metadata = envelopeMetadata(parsed);
64834
- const nonce = randomBytes5(12);
65213
+ const nonce = randomBytes6(12);
64835
65214
  const cipher = createCipheriv3("aes-256-gcm", encryption.key, nonce);
64836
65215
  cipher.setAAD(Buffer.from(canonicalJson(metadata)));
64837
65216
  const ciphertext = Buffer.concat([
@@ -65150,12 +65529,12 @@ function parseRetainedNativeContexts(value) {
65150
65529
  if (value === void 0) return [];
65151
65530
  if (!Array.isArray(value))
65152
65531
  throw new Error("Private skill native contexts are invalid.");
65153
- const contexts = value.map(parsePrivateSkillNativeContext);
65154
- const sources = new Set(contexts.map((context) => context.source_digest));
65155
- const contents = new Set(contexts.map((context) => context.context_digest));
65156
- if (sources.size !== contexts.length || contents.size !== contexts.length)
65532
+ const contexts2 = value.map(parsePrivateSkillNativeContext);
65533
+ const sources = new Set(contexts2.map((context) => context.source_digest));
65534
+ const contents = new Set(contexts2.map((context) => context.context_digest));
65535
+ if (sources.size !== contexts2.length || contents.size !== contexts2.length)
65157
65536
  throw new Error("Private skill native context lineage is duplicated.");
65158
- return contexts;
65537
+ return contexts2;
65159
65538
  }
65160
65539
  function parsePrivateSkillReformulationAttempts(value, draftId, originalCandidateDigest) {
65161
65540
  if (value === void 0) return [];
@@ -65611,7 +65990,7 @@ function privateSkillInspectorRefreshAllowed(draft) {
65611
65990
  return draft.inspection.outcome === "positive_recovery_need" || draft.inspection.outcome === "operational_failure" || draft.last_error_code === "submission_reinspection_source_projection_drift" || draft.last_error_code === "inspector_refresh_new_lineage_required";
65612
65991
  }
65613
65992
  function envelopeMetadataFromEnvelope(envelope) {
65614
- const base = {
65993
+ const base2 = {
65615
65994
  version: envelope.version,
65616
65995
  draft_id: envelope.draft_id,
65617
65996
  state: envelope.state,
@@ -65621,7 +66000,7 @@ function envelopeMetadataFromEnvelope(envelope) {
65621
66000
  updated_at: envelope.updated_at
65622
66001
  };
65623
66002
  return hasEnvelopeReformulationMetadata(envelope) ? {
65624
- ...base,
66003
+ ...base2,
65625
66004
  reformulation_available: envelope.reformulation_available,
65626
66005
  reformulation_reason: envelope.reformulation_reason,
65627
66006
  reformulation_attempt_count: envelope.reformulation_attempt_count,
@@ -65631,7 +66010,7 @@ function envelopeMetadataFromEnvelope(envelope) {
65631
66010
  ...envelope.inspector_digest === void 0 ? {} : { inspector_digest: envelope.inspector_digest },
65632
66011
  ...envelope.native_context_pending === void 0 ? {} : { native_context_pending: envelope.native_context_pending },
65633
66012
  ...envelope.next_action === void 0 ? {} : { next_action: envelope.next_action }
65634
- } : base;
66013
+ } : base2;
65635
66014
  }
65636
66015
  function parseEnvelope2(value) {
65637
66016
  const parsed = JSON.parse(value);
@@ -65957,13 +66336,13 @@ async function privateSkillRecoveryItems(options = {}) {
65957
66336
  }
65958
66337
  function privateSkillRecoveryItem(draftId, reasonCode, storageError) {
65959
66338
  if (reasonCode === "undecryptable_entry") {
65960
- const diagnostic = storageError?.diagnostic();
66339
+ const diagnostic2 = storageError?.diagnostic();
65961
66340
  return {
65962
66341
  lane: "private_skill",
65963
66342
  draft_id: draftId,
65964
66343
  reason_code: reasonCode,
65965
- remediation: diagnostic?.remediation ?? "Restore access to the original encryption key, then inspect the retained draft again. Do not delete or regenerate it.",
65966
- ...diagnostic ? { diagnostic } : {}
66344
+ remediation: diagnostic2?.remediation ?? "Restore access to the original encryption key, then inspect the retained draft again. Do not delete or regenerate it.",
66345
+ ...diagnostic2 ? { diagnostic: diagnostic2 } : {}
65967
66346
  };
65968
66347
  }
65969
66348
  return {
@@ -66096,7 +66475,7 @@ async function quarantinePrivateSkillTemporary(directory, target, temporaryName,
66096
66475
  join4(directory, temporaryName),
66097
66476
  join4(
66098
66477
  quarantine,
66099
- `${target.replace(/\.json$/u, "")}.${reason}.${randomBytes5(8).toString("hex")}.retained`
66478
+ `${target.replace(/\.json$/u, "")}.${reason}.${randomBytes6(8).toString("hex")}.retained`
66100
66479
  )
66101
66480
  );
66102
66481
  }
@@ -66230,7 +66609,7 @@ async function atomicWritePrivateJson(path, value) {
66230
66609
  }
66231
66610
  async function atomicWritePrivateText(path, value) {
66232
66611
  await ensurePrivateDirectory(dirname4(path));
66233
- const temporary = `${path}.${process.pid}.${randomBytes5(8).toString("hex")}.tmp`;
66612
+ const temporary = `${path}.${process.pid}.${randomBytes6(8).toString("hex")}.tmp`;
66234
66613
  let handle = null;
66235
66614
  try {
66236
66615
  handle = await open3(temporary, "wx", 384);
@@ -66750,7 +67129,9 @@ async function executeLocalOnlyTool(name, payload, context) {
66750
67129
  case "get_pending_action_payload":
66751
67130
  return LOCAL_ONLY_HANDLERS.get_pending_action_payload(payload, context);
66752
67131
  case "capture_learning":
66753
- return LOCAL_ONLY_HANDLERS.capture_learning(payload, context);
67132
+ return withCaptureLearningDiagnostics(
67133
+ async () => LOCAL_ONLY_HANDLERS.capture_learning(payload, context)
67134
+ );
66754
67135
  case "inspect_private_learning_outbox":
66755
67136
  return LOCAL_ONLY_HANDLERS.inspect_private_learning_outbox(
66756
67137
  payload,
@@ -66811,7 +67192,8 @@ function acknowledgeFeedbackDenialLocally(input, persistence) {
66811
67192
  };
66812
67193
  }
66813
67194
  }
66814
- async function preparePrivateLessonDraft(input, persistence, destination, tool, replacementOf) {
67195
+ async function preparePrivateLessonDraft(input, persistence, destination, tool, replacementOf, captureId) {
67196
+ markCaptureLearningStage("preparation");
66815
67197
  const prepared = preparePrivateLessonCandidate(input, { tool });
66816
67198
  if (replacementOf) {
66817
67199
  return preparePrivateLessonReplacement(
@@ -66822,26 +67204,37 @@ async function preparePrivateLessonDraft(input, persistence, destination, tool,
66822
67204
  destination
66823
67205
  );
66824
67206
  }
67207
+ markCaptureLearningStage("encrypted_persistence");
67208
+ if (captureId) {
67209
+ markCaptureLearningPersisting(privateLessonCaptureDraftId(captureId));
67210
+ }
66825
67211
  const draft = await persistence.queuePreparedPrivateLesson(
66826
67212
  prepared,
66827
- destination
67213
+ destination,
67214
+ captureId
66828
67215
  );
67216
+ markCaptureLearningPersisted(draft.draft_id);
67217
+ markCaptureLearningStage("response");
66829
67218
  return privateLessonDraftActionResult(draft, destination, {
66830
- next_action: prepared.status === "ready" || prepared.status === "held_safety" && privateLessonHealthReportingEnabled() ? {
67219
+ next_action: prepared.status === "ready" && (draft.state === "ready" || draft.state === "awaiting_authorization") || prepared.status === "held_safety" && draft.state === "held_safety" && privateLessonHealthReportingEnabled() ? {
66831
67220
  tool: "submit_private_lesson_candidate",
66832
67221
  arguments: { draft_id: draft.draft_id }
66833
- } : null,
67222
+ } : privateLessonNextAction(draft),
66834
67223
  // Where the lesson holds, without its text, for a replacement.
66835
67224
  ...prepared.status === "held_safety" ? privateLessonFindings(input) : {}
66836
67225
  });
66837
67226
  }
66838
67227
  async function preparePrivateLessonReplacement(input, prepared, replacementOf, persistence, destination) {
67228
+ markCaptureLearningStage("encrypted_persistence");
67229
+ markCaptureLearningPersisting();
66839
67230
  try {
66840
67231
  const { draft, attempts_remaining, replayed } = await persistence.queuePrivateLessonReplacement(
66841
67232
  replacementOf,
66842
67233
  prepared,
66843
67234
  destination
66844
67235
  );
67236
+ markCaptureLearningPersisted(draft.draft_id);
67237
+ markCaptureLearningStage("response");
66845
67238
  return privateLessonDraftActionResult(draft, destination, {
66846
67239
  replacement_attempts_remaining: attempts_remaining,
66847
67240
  replayed,
@@ -66856,8 +67249,11 @@ async function preparePrivateLessonReplacement(input, prepared, replacementOf, p
66856
67249
  if (!(error instanceof PrivateLessonReplacementRefusedError) || error.reason !== "replacement_held") {
66857
67250
  throw error;
66858
67251
  }
67252
+ markCaptureLearningNotPersisted();
67253
+ markCaptureLearningStage("response");
66859
67254
  return {
66860
67255
  status: "not_stored",
67256
+ persistence_outcome: "not_persisted",
66861
67257
  ...error.diagnostic(),
66862
67258
  held_reasons: prepared.held_reasons,
66863
67259
  ...privateLessonFindings(input),
@@ -66871,7 +67267,12 @@ async function preparePrivateLessonReplacement(input, prepared, replacementOf, p
66871
67267
  }
66872
67268
  async function captureLearning(input, persistence, lessonDestination, skillDestination) {
66873
67269
  const parsed = captureLearningInputSchema.parse(input);
67270
+ adoptCaptureLearningId(parsed.capture_id);
66874
67271
  const route = captureLearningRoute(parsed);
67272
+ markCaptureLearningRoute(route);
67273
+ if (route === "private_lesson" && parsed.replacement_of) {
67274
+ markCaptureLearningReplacement(parsed.replacement_of.draft_id);
67275
+ }
66875
67276
  if (route === "preference") {
66876
67277
  return {
66877
67278
  contract_version: parsed.contract_version,
@@ -66884,6 +67285,8 @@ async function captureLearning(input, persistence, lessonDestination, skillDesti
66884
67285
  };
66885
67286
  }
66886
67287
  if (route === "private_skill") {
67288
+ markCaptureLearningStage("encrypted_persistence");
67289
+ markCaptureLearningPersisting();
66887
67290
  const link2 = parsed.replacement_of && "context_source" in parsed.replacement_of ? parsed.replacement_of : void 0;
66888
67291
  const draft = link2 ? await persistence.queuePrivateSkillReformulation(
66889
67292
  link2.draft_id,
@@ -66894,6 +67297,8 @@ async function captureLearning(input, persistence, lessonDestination, skillDesti
66894
67297
  parsed.private_skill,
66895
67298
  skillDestination
66896
67299
  );
67300
+ markCaptureLearningPersisted(draft.draft_id);
67301
+ markCaptureLearningStage("response");
66897
67302
  const recoveryContext = privateSkillRecoveryContext(draft);
66898
67303
  return {
66899
67304
  contract_version: parsed.contract_version,
@@ -66909,11 +67314,15 @@ async function captureLearning(input, persistence, lessonDestination, skillDesti
66909
67314
  persistence,
66910
67315
  lessonDestination,
66911
67316
  "capture_learning",
66912
- parsed.replacement_of?.draft_id
67317
+ parsed.replacement_of?.draft_id,
67318
+ parsed.replacement_of ? void 0 : currentCaptureLearningId()
66913
67319
  );
66914
67320
  return {
66915
67321
  contract_version: parsed.contract_version,
66916
67322
  capture_route: "private_lesson",
67323
+ ...!parsed.replacement_of ? { capture_id: currentCaptureLearningId() } : {},
67324
+ correlation_id: captureLearningCurrentDiagnostic()?.correlation_id,
67325
+ persistence_outcome: "persisted",
66917
67326
  ...prepared
66918
67327
  };
66919
67328
  }
@@ -66999,7 +67408,7 @@ function optionalPrivateSkillDraftId(value) {
66999
67408
  return value;
67000
67409
  }
67001
67410
  function unavailableInspection(lane, error) {
67002
- const diagnostic = privateOutboxDiagnostic(error);
67411
+ const diagnostic2 = privateOutboxDiagnostic(error);
67003
67412
  return {
67004
67413
  status: "unavailable",
67005
67414
  drafts: [],
@@ -67007,8 +67416,8 @@ function unavailableInspection(lane, error) {
67007
67416
  recovery_items: [],
67008
67417
  error_code: `${lane}_inspection_failed`,
67009
67418
  reason_code: "private_learning_inspection_unavailable",
67010
- action_required: diagnostic === null ? "Run run_connection_doctor, follow its local private-learning remediation, then inspect the outbox again. No retained draft was changed." : "Follow the bounded local diagnostic remediation directly; run run_connection_doctor only if the diagnostic is absent, then inspect the outbox again. No retained draft was changed.",
67011
- ...diagnostic ? { diagnostic } : {}
67419
+ action_required: diagnostic2 === null ? "Run run_connection_doctor, follow its local private-learning remediation, then inspect the outbox again. No retained draft was changed." : "Follow the bounded local diagnostic remediation directly; run run_connection_doctor only if the diagnostic is absent, then inspect the outbox again. No retained draft was changed.",
67420
+ ...diagnostic2 ? { diagnostic: diagnostic2 } : {}
67012
67421
  };
67013
67422
  }
67014
67423
  function privateOutboxDiagnostic(error) {
@@ -67017,6 +67426,12 @@ function privateOutboxDiagnostic(error) {
67017
67426
  return { reason_code, stage, remediation };
67018
67427
  }
67019
67428
  async function inspectPrivateLessonOutbox(input, persistence, destination) {
67429
+ if (input.capture_id) {
67430
+ input = {
67431
+ ...input,
67432
+ draft_id: privateLessonCaptureDraftId(input.capture_id)
67433
+ };
67434
+ }
67020
67435
  const snapshot = await persistence.inspectPrivateLessonOutbox(
67021
67436
  input.limit,
67022
67437
  input.offset
@@ -67028,6 +67443,8 @@ async function inspectPrivateLessonOutbox(input, persistence, destination) {
67028
67443
  );
67029
67444
  if (completion) {
67030
67445
  return {
67446
+ ...input.capture_id ? { capture_id: input.capture_id } : {},
67447
+ persistence_outcome: "persisted",
67031
67448
  draft: privateLessonSubmittedActionResult(completion),
67032
67449
  outbox: publicOutboxSummary(snapshot.summary),
67033
67450
  recovery_items: snapshot.recovery_items
@@ -67035,12 +67452,20 @@ async function inspectPrivateLessonOutbox(input, persistence, destination) {
67035
67452
  }
67036
67453
  const draft = await persistence.readPrivateLessonDraft(input.draft_id);
67037
67454
  return {
67455
+ ...input.capture_id ? { capture_id: input.capture_id } : {},
67456
+ persistence_outcome: "persisted",
67038
67457
  draft: privateLessonDraftActionResult(draft, destination),
67039
67458
  outbox: publicOutboxSummary(snapshot.summary),
67040
67459
  recovery_items: snapshot.recovery_items
67041
67460
  };
67042
67461
  } catch (error) {
67043
67462
  return {
67463
+ ...input.capture_id ? { capture_id: input.capture_id } : {},
67464
+ persistence_outcome: "unknown",
67465
+ ...error instanceof PrivateLessonDraftUnavailableError && error.reason === "unknown" ? {
67466
+ local_record_outcome: "not_found",
67467
+ recovery: "No retained local record was found. This does not establish that a previous call never persisted or submitted. Reconcile with the same capture_id within the retained outcome window; submitted completion markers are retained for 14 days."
67468
+ } : {},
67044
67469
  selected_draft_error: privateLessonSelectedDraftError(
67045
67470
  input.draft_id,
67046
67471
  error
@@ -67067,7 +67492,7 @@ function privateLessonPageNextAction(nextOffset, limit) {
67067
67492
  };
67068
67493
  }
67069
67494
  function privateLessonSelectedDraftError(draftId, error) {
67070
- const diagnostic = error instanceof PrivateLessonDraftUnavailableError || error instanceof PrivateOutboxDecryptionError ? error.diagnostic() : error instanceof PrivateOutboxStorageError ? {
67495
+ const diagnostic2 = error instanceof PrivateLessonDraftUnavailableError || error instanceof PrivateOutboxDecryptionError ? error.diagnostic() : error instanceof PrivateOutboxStorageError ? {
67071
67496
  ...error.diagnostic(),
67072
67497
  code: error.reasonCode,
67073
67498
  draft_id: draftId,
@@ -67085,9 +67510,9 @@ function privateLessonSelectedDraftError(draftId, error) {
67085
67510
  };
67086
67511
  return {
67087
67512
  status: "unavailable",
67088
- error_code: diagnostic.code,
67089
- reason_code: diagnostic.code,
67090
- ...diagnostic
67513
+ error_code: diagnostic2.code,
67514
+ reason_code: diagnostic2.code,
67515
+ ...diagnostic2
67091
67516
  };
67092
67517
  }
67093
67518
  function privateLessonHealthReportingEnabled(env = process.env) {
@@ -67119,6 +67544,15 @@ function privateLessonDraftActionResult(draft, destination, extra = {}) {
67119
67544
  };
67120
67545
  }
67121
67546
  function privateLessonNextAction(draft) {
67547
+ if (ownerAttestedLegacyPrivateLessonRecoveryEligible(draft)) {
67548
+ return {
67549
+ tool: "retry_private_lesson_candidate",
67550
+ arguments: {
67551
+ draft_id: draft.draft_id,
67552
+ legacy_destination_recovery: { action: "review" }
67553
+ }
67554
+ };
67555
+ }
67122
67556
  if (draft.state === "ready") {
67123
67557
  return {
67124
67558
  tool: "submit_private_lesson_candidate",
@@ -67139,15 +67573,6 @@ function privateLessonNextAction(draft) {
67139
67573
  };
67140
67574
  }
67141
67575
  if (draft.state === "held_validation") {
67142
- if (draft.last_error_code === "private_lesson_destination_legacy_unbound") {
67143
- return {
67144
- tool: "capture_learning",
67145
- action_code: "recapture_legacy_private_lesson_with_destination_binding",
67146
- retained_source_draft_id: draft.draft_id,
67147
- retained_source_available_to_agent: false,
67148
- required_input: ["lesson"]
67149
- };
67150
- }
67151
67576
  if (draft.last_error_code === "private_lesson_destination_api_changed" || draft.last_error_code === "private_lesson_destination_credential_changed" || draft.last_error_code === "private_lesson_destination_audience_mismatch") {
67152
67577
  return {
67153
67578
  tool: "retry_private_lesson_candidate",
@@ -67181,15 +67606,15 @@ function privateLessonActionRequired(draft, destination) {
67181
67606
  !privateLessonReplaceable(draft, destination)
67182
67607
  );
67183
67608
  }
67609
+ if (ownerAttestedLegacyPrivateLessonRecoveryEligible(draft) && draft.last_error_code === "private_lesson_destination_legacy_unbound") {
67610
+ return "This legacy draft has no authenticated destination binding. Request its content-free legacy destination review, then obtain the owner's new approval for that exact draft and organization before local migration. Its retained source stays encrypted and unavailable to the agent; the draft was not sent.";
67611
+ }
67184
67612
  if (draft.state === "awaiting_authorization") {
67185
67613
  return "Restore authorization for the exact private-lesson submission action, then retry this retained draft.";
67186
67614
  }
67187
67615
  if (draft.state === "retry_scheduled") {
67188
67616
  return "Retry the exact retained draft at or after next_retry_at.";
67189
67617
  }
67190
- if (draft.state === "held_validation" && draft.last_error_code === "private_lesson_destination_legacy_unbound") {
67191
- return "This legacy draft has no authenticated destination binding. Update the client and re-capture the lesson from current safe task context with capture_learning; the retained draft was not sent.";
67192
- }
67193
67618
  if (draft.state === "held_validation" && draft.last_error_code === "private_lesson_destination_api_changed") {
67194
67619
  return "The API destination differs from the captured destination. Restore the captured API base, then retry the exact retained draft; it will not be sent across API bases.";
67195
67620
  }
@@ -67308,12 +67733,12 @@ function privateSkillSelectedSubmittedResult(completion) {
67308
67733
  }
67309
67734
  function privateSkillSelectedDraftError(draftId, error) {
67310
67735
  if (error instanceof PrivateSkillDraftDeletedError) {
67311
- const diagnostic = error.diagnostic();
67736
+ const diagnostic2 = error.diagnostic();
67312
67737
  return {
67313
67738
  status: "unavailable",
67314
- error_code: diagnostic.code,
67315
- reason_code: diagnostic.code,
67316
- ...diagnostic
67739
+ error_code: diagnostic2.code,
67740
+ reason_code: diagnostic2.code,
67741
+ ...diagnostic2
67317
67742
  };
67318
67743
  }
67319
67744
  return {
@@ -67366,7 +67791,7 @@ function publicOutboxSummary(summary) {
67366
67791
  }
67367
67792
 
67368
67793
  // ../codex-plugin/scripts/feedback-disposition.mjs
67369
- import { createHash as createHash4, randomBytes as randomBytes6 } from "node:crypto";
67794
+ import { createHash as createHash4, randomBytes as randomBytes7 } from "node:crypto";
67370
67795
  import {
67371
67796
  chmodSync,
67372
67797
  closeSync as closeSync3,
@@ -67583,7 +68008,7 @@ function cleanupExpiredMarkers(directory, now) {
67583
68008
  }
67584
68009
  }
67585
68010
  function writeMarkerAtomically(path, marker) {
67586
- const temporaryPath = `${path}.${randomBytes6(8).toString("hex")}.tmp`;
68011
+ const temporaryPath = `${path}.${randomBytes7(8).toString("hex")}.tmp`;
67587
68012
  let descriptor;
67588
68013
  try {
67589
68014
  descriptor = openSync3(
@@ -67743,9 +68168,10 @@ function createLocalPersistenceCapabilities(dependencies = {}) {
67743
68168
  readKey: (source) => readExistingPrivateLessonOutboxKeyForSource(source, process.env, {})
67744
68169
  }),
67745
68170
  queuePrivateSkillHandoff: (payload, uploadBaseUrl) => queuePrivateSkillHandoff(payload, { uploadBaseUrl }),
67746
- queuePreparedPrivateLesson: async (prepared, destination) => queuePreparedPrivateLesson(prepared, null, {
68171
+ queuePreparedPrivateLesson: async (prepared, destination, captureId) => queuePreparedPrivateLesson(prepared, null, {
67747
68172
  ...await withEncryption(),
67748
- ...destination ? { destination } : {}
68173
+ ...destination ? { destination } : {},
68174
+ ...captureId ? { captureId } : {}
67749
68175
  }),
67750
68176
  queuePrivateLessonReplacement: async (replacementOf, prepared, destination) => queuePrivateLessonReplacement(replacementOf, prepared, {
67751
68177
  ...await withEncryption(),
@@ -67795,8 +68221,8 @@ function createLocalPersistenceCapabilities(dependencies = {}) {
67795
68221
  }
67796
68222
 
67797
68223
  // ../core/src/redaction-request-budget.ts
67798
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
67799
- var requests = new AsyncLocalStorage2();
68224
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
68225
+ var requests = new AsyncLocalStorage3();
67800
68226
  trackRedactionRequests(() => requests.getStore());
67801
68227
  function withRedactionRequestBudget(run) {
67802
68228
  return requests.getStore() ? run() : requests.run({}, run);
@@ -67854,8 +68280,8 @@ function inspectReviewRepairForTransport(value) {
67854
68280
  }
67855
68281
 
67856
68282
  // src/network-transport.ts
67857
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
67858
- var networkExecutionAuthority = new AsyncLocalStorage3();
68283
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
68284
+ var networkExecutionAuthority = new AsyncLocalStorage4();
67859
68285
  var guardedFetches = /* @__PURE__ */ new WeakSet();
67860
68286
  function installRuntimeFetchGuard() {
67861
68287
  const delegate = globalThis.fetch;
@@ -67905,7 +68331,7 @@ import {
67905
68331
  rmSync as rmSync2,
67906
68332
  writeFileSync as writeFileSync2
67907
68333
  } from "node:fs";
67908
- import { createHash as createHash5, randomBytes as randomBytes7 } from "node:crypto";
68334
+ import { createHash as createHash5, randomBytes as randomBytes8 } from "node:crypto";
67909
68335
  import { isIP } from "node:net";
67910
68336
  import { homedir as homedir9 } from "node:os";
67911
68337
  import { join as join10 } from "node:path";
@@ -68563,7 +68989,7 @@ function recordConnectionDoctorLifecycleProbe(options = {}) {
68563
68989
  );
68564
68990
  const path = join10(healthDir, `${rawSurface}.json`);
68565
68991
  if (!existsSync5(path)) return false;
68566
- const temporaryPath = `${path}.${process.pid}.${randomBytes7(6).toString("hex")}.tmp`;
68992
+ const temporaryPath = `${path}.${process.pid}.${randomBytes8(6).toString("hex")}.tmp`;
68567
68993
  try {
68568
68994
  const parsed = JSON.parse(
68569
68995
  readSecureLocalText(path, {
@@ -69569,6 +69995,173 @@ function isRecord10(value) {
69569
69995
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
69570
69996
  }
69571
69997
 
69998
+ // src/legacy-lesson-destination-recovery.ts
69999
+ var CONTRACT_VERSION = "private-lesson-legacy-destination-recovery-v1";
70000
+ var DIGEST3 = /^sha256:[a-f0-9]{64}$/u;
70001
+ async function legacyLessonDestinationRecovery(draft, destination, request, dependencies) {
70002
+ const alreadyRecovered = isRecoveredForDestination(draft, destination);
70003
+ if (!ownerAttestedLegacyPrivateLessonRecoveryEligible(draft) && !alreadyRecovered) {
70004
+ return refused(draft, "private_lesson_destination_recovery_ineligible");
70005
+ }
70006
+ if (request.action === "approve" && !validApproval(request)) {
70007
+ return refused(draft, "private_lesson_destination_recovery_approval_required");
70008
+ }
70009
+ if (request.action === "approve" && (request.expected_payload_digest !== draft.payload_digest || canonicalJson(request.expected_destination) !== canonicalJson(destination))) {
70010
+ return refused(draft, "private_lesson_destination_recovery_review_stale");
70011
+ }
70012
+ let audience;
70013
+ try {
70014
+ audience = await dependencies.verifiedOrganizationAudience();
70015
+ if (!DIGEST3.test(audience)) throw new Error("Invalid verified audience.");
70016
+ } catch {
70017
+ return refused(draft, "private_lesson_destination_recovery_policy_unavailable");
70018
+ }
70019
+ if (alreadyRecovered && draft.attested_organization_audience_hash !== audience || draft.policy !== null && draft.policy.organization_audience_hash !== audience) {
70020
+ return refused(draft, "private_lesson_destination_recovery_review_stale");
70021
+ }
70022
+ const plan = recoveryPlan(draft, destination, audience);
70023
+ if (request.action === "review") {
70024
+ if (alreadyRecovered) return recovered(draft, plan, "already_recovered");
70025
+ return {
70026
+ ...base(draft),
70027
+ status: "destination_recovery_review",
70028
+ persistence_outcome: "unchanged",
70029
+ plan,
70030
+ requires_explicit_owner_approval: true,
70031
+ owner_consent_required: `Confirm that draft ${draft.draft_id} belongs only to the organization currently authenticated by this installation (audience ${audience}), and authorize binding and privately delivering this unchanged draft there. Confirm that every client reading this outbox is Remembrance 0.2.6 or newer. This is new approval: the original draft did not record its destination. The retained lesson text stays encrypted and is not shown.`,
70032
+ next_action: {
70033
+ tool: "retry_private_lesson_candidate",
70034
+ arguments: {
70035
+ draft_id: draft.draft_id,
70036
+ legacy_destination_recovery: {
70037
+ action: "approve",
70038
+ review_id: plan.review_id,
70039
+ expected_payload_digest: draft.payload_digest,
70040
+ expected_destination: destination,
70041
+ organization_audience_hash: audience
70042
+ }
70043
+ },
70044
+ requires_explicit_owner_approval: true,
70045
+ required_owner_input: [
70046
+ "owner_attested_single_organization",
70047
+ "all_outbox_readers_updated",
70048
+ "owner_attestation_sha256"
70049
+ ],
70050
+ instruction: "Ask the owner for the stated confirmation. Only after that confirmation, add both true confirmations and the SHA-256 hash of the owner's exact approval. Existing submission approval does not authorize migration."
70051
+ }
70052
+ };
70053
+ }
70054
+ if (request.review_id !== plan.review_id || request.organization_audience_hash !== audience) {
70055
+ return refused(draft, "private_lesson_destination_recovery_review_stale");
70056
+ }
70057
+ if (alreadyRecovered) {
70058
+ return recovered(draft, plan, "already_recovered");
70059
+ }
70060
+ try {
70061
+ const receipt = await dependencies.recover({
70062
+ draft_id: draft.draft_id,
70063
+ expected_payload_digest: draft.payload_digest,
70064
+ destination,
70065
+ organization_audience_hash: audience,
70066
+ owner_attested_single_organization: true,
70067
+ owner_attestation_sha256: request.owner_attestation_sha256
70068
+ });
70069
+ return {
70070
+ ...recovered(draft, plan, "destination_recovered"),
70071
+ recovery_receipt: receipt
70072
+ };
70073
+ } catch {
70074
+ try {
70075
+ const current = await dependencies.readDraft(draft.draft_id);
70076
+ if (current.payload_digest === draft.payload_digest && isRecoveredForDestination(current, destination) && current.attested_organization_audience_hash === audience) {
70077
+ return recovered(current, plan, "already_recovered");
70078
+ }
70079
+ if (ownerAttestedLegacyPrivateLessonRecoveryEligible(current) && current.payload_digest === draft.payload_digest) {
70080
+ return refused(current, "private_lesson_destination_recovery_not_applied");
70081
+ }
70082
+ } catch {
70083
+ }
70084
+ return {
70085
+ ...base(draft),
70086
+ status: "destination_recovery_unknown",
70087
+ error_code: "private_lesson_destination_recovery_outcome_unknown",
70088
+ failure_stage: "destination_recovery",
70089
+ persistence_outcome: "unknown",
70090
+ retained_locally: null,
70091
+ action_required: "The local migration outcome could not be established. Reconcile by repeating this exact approved action; do not recapture, change the destination, or delete the retained draft.",
70092
+ next_action: {
70093
+ tool: "retry_private_lesson_candidate",
70094
+ arguments: {
70095
+ draft_id: draft.draft_id,
70096
+ legacy_destination_recovery: request
70097
+ }
70098
+ }
70099
+ };
70100
+ }
70101
+ }
70102
+ function isRecoveredForDestination(draft, destination) {
70103
+ 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";
70104
+ }
70105
+ function validApproval(request) {
70106
+ 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);
70107
+ }
70108
+ function recoveryPlan(draft, destination, audience) {
70109
+ const fields2 = {
70110
+ contract_version: CONTRACT_VERSION,
70111
+ draft_id: draft.draft_id,
70112
+ payload_digest: draft.payload_digest,
70113
+ destination,
70114
+ organization_audience_hash: audience,
70115
+ original_identity_sha256: hashValue(canonicalJson({
70116
+ draft_id: draft.draft_id,
70117
+ payload_digest: draft.payload_digest,
70118
+ redaction_version: draft.redaction_version,
70119
+ redactor_digest: draft.redactor_digest,
70120
+ idempotency_key: draft.idempotency_key,
70121
+ created_at: draft.created_at
70122
+ })),
70123
+ minimum_reader_version: "0.2.6"
70124
+ };
70125
+ return { ...fields2, review_id: hashValue(canonicalJson(fields2)) };
70126
+ }
70127
+ function base(draft) {
70128
+ return {
70129
+ contract_version: CONTRACT_VERSION,
70130
+ draft_id: draft.draft_id,
70131
+ payload_digest: draft.payload_digest,
70132
+ retained_locally: true,
70133
+ candidate_sent: false,
70134
+ retained_source_available_to_agent: false
70135
+ };
70136
+ }
70137
+ function recovered(draft, plan, status) {
70138
+ return {
70139
+ ...base(draft),
70140
+ status,
70141
+ persistence_outcome: "destination_bound",
70142
+ plan,
70143
+ action_required: "The unchanged encrypted draft is bound to the owner-approved destination. Follow its exact normal private retry; migration alone does not submit the lesson.",
70144
+ next_action: {
70145
+ tool: "retry_private_lesson_candidate",
70146
+ arguments: { draft_id: draft.draft_id }
70147
+ }
70148
+ };
70149
+ }
70150
+ function refused(draft, code) {
70151
+ return {
70152
+ ...base(draft),
70153
+ status: "destination_recovery_refused",
70154
+ error_code: code,
70155
+ failure_stage: "destination_recovery_review",
70156
+ persistence_outcome: "unchanged",
70157
+ action_required: "The selected draft was not migrated. Inspect its retained state and request a fresh destination review after correcting authorization or configuration; never infer its older destination or expose its source.",
70158
+ next_action: {
70159
+ tool: "inspect_private_lesson_outbox",
70160
+ arguments: { draft_id: draft.draft_id }
70161
+ }
70162
+ };
70163
+ }
70164
+
69572
70165
  // src/server.ts
69573
70166
  function inspectPrivateLearningOutbox2(input, dependencies = {}) {
69574
70167
  return inspectPrivateLearningOutbox(
@@ -69580,7 +70173,7 @@ function inspectPrivateLearningOutbox2(input, dependencies = {}) {
69580
70173
  }
69581
70174
  var MAX_REMOTE_RESPONSE_BYTES = 4 * 1024 * 1024;
69582
70175
  var DOCTOR_PROBE_TIMEOUT_MS = 7500;
69583
- var SERVER_VERSION = true ? "0.2.7" : "0.0.0-dev";
70176
+ var SERVER_VERSION = true ? "0.2.9" : "0.0.0-dev";
69584
70177
  var tools2 = toolDefinitions;
69585
70178
  var doctorCliRequested = process.argv[2] === "doctor";
69586
70179
  var nativeContextCliRequested = process.argv[2] === "--native-context";
@@ -69828,19 +70421,41 @@ async function dispatchJsonRpcRequest(request) {
69828
70421
  error: { code: -32602, message: `Unknown tool: ${name}` }
69829
70422
  };
69830
70423
  }
69831
- let result;
69832
70424
  try {
69833
- result = await callTool(definition, request.params?.arguments);
70425
+ const execute = async () => {
70426
+ const result2 = await callTool(definition, request.params?.arguments);
70427
+ markCaptureLearningStage("response");
70428
+ return remembranceMcpToolCallResult(result2, definition.name);
70429
+ };
70430
+ const result = name === "capture_learning" ? await withCaptureLearningDiagnostics(execute) : await execute();
70431
+ return { id: request.id, result };
69834
70432
  } catch (error) {
70433
+ const capture2 = captureLearningDiagnostic(error);
70434
+ if (capture2) {
70435
+ try {
70436
+ process.stderr.write(
70437
+ `${JSON.stringify({
70438
+ event: "capture_learning_failed",
70439
+ occurred_at: (/* @__PURE__ */ new Date()).toISOString(),
70440
+ server_version: SERVER_VERSION,
70441
+ code: capture2.code,
70442
+ correlation_id: capture2.correlation_id,
70443
+ capture_id: capture2.capture_id,
70444
+ failure_stage: capture2.failure_stage,
70445
+ persistence_outcome: capture2.persistence_outcome,
70446
+ ...capture2.draft_id ? { draft_id: capture2.draft_id } : {},
70447
+ ...capture2.reconciliation_draft_id ? { reconciliation_draft_id: capture2.reconciliation_draft_id } : {}
70448
+ })}
70449
+ `
70450
+ );
70451
+ } catch {
70452
+ }
70453
+ }
69835
70454
  return {
69836
70455
  id: request.id,
69837
70456
  error: jsonRpcErrorForToolError(error)
69838
70457
  };
69839
70458
  }
69840
- return {
69841
- id: request.id,
69842
- result: remembranceMcpToolCallResult(result, definition.name)
69843
- };
69844
70459
  }
69845
70460
  if (request.id !== void 0) {
69846
70461
  return {
@@ -69854,6 +70469,17 @@ async function dispatchJsonRpcRequest(request) {
69854
70469
  return null;
69855
70470
  }
69856
70471
  function jsonRpcErrorForToolError(error) {
70472
+ const classified = classifiedJsonRpcErrorForToolError(error);
70473
+ const capture2 = captureLearningDiagnostic(error);
70474
+ if (!capture2) return classified;
70475
+ const outcome = capture2.persistence_outcome === "persisted" ? "The encrypted draft was saved." : capture2.persistence_outcome === "not_persisted" ? "No draft was saved by this call." : "Whether the encrypted draft was saved is unknown; reconcile before creating another capture.";
70476
+ return {
70477
+ ...classified,
70478
+ message: classified.message === "MCP operation failed." ? `Private learning capture failed during ${capture2.failure_stage} (${capture2.code}). ${outcome} ${"remediation" in capture2 ? capture2.remediation : capture2.recovery} Reference: ${capture2.correlation_id}.` : classified.message,
70479
+ data: { ...capture2, ...classified.data }
70480
+ };
70481
+ }
70482
+ function classifiedJsonRpcErrorForToolError(error) {
69857
70483
  if (error instanceof PrivateLessonDraftUnavailableError || error instanceof PrivateSkillRecoveryContextError || error instanceof PrivateSkillDraftUnavailableError) {
69858
70484
  return {
69859
70485
  code: error.jsonRpcCode(),
@@ -69892,14 +70518,17 @@ function jsonRpcErrorForToolError(error) {
69892
70518
  var McpPublicError = class extends Error {
69893
70519
  };
69894
70520
  async function callTool(definition, rawArguments, dependencies = {}) {
69895
- const runtimeDefinition = canonicalToolDefinitionForDispatch(definition);
69896
- return runWithRemembranceNetworkExecution(
69897
- {
69898
- toolName: runtimeDefinition.name,
69899
- networkBehavior: runtimeDefinition.executionNetworkBehavior
69900
- },
69901
- () => callToolWithinExecution(runtimeDefinition, rawArguments, dependencies)
69902
- );
70521
+ const execute = () => {
70522
+ const runtimeDefinition = canonicalToolDefinitionForDispatch(definition);
70523
+ return runWithRemembranceNetworkExecution(
70524
+ {
70525
+ toolName: runtimeDefinition.name,
70526
+ networkBehavior: runtimeDefinition.executionNetworkBehavior
70527
+ },
70528
+ () => callToolWithinExecution(runtimeDefinition, rawArguments, dependencies)
70529
+ );
70530
+ };
70531
+ return definition.name === "capture_learning" ? withCaptureLearningDiagnostics(execute) : execute();
69903
70532
  }
69904
70533
  async function callToolWithinExecution(runtimeDefinition, rawArguments, dependencies) {
69905
70534
  if ((dependencies.testSchemaOverride || dependencies.testLocalOnlyExecutor) && process.env.NODE_ENV !== "test") {
@@ -69957,7 +70586,10 @@ async function callNetworkToolWithinExecution(definition, payload, access, trans
69957
70586
  access,
69958
70587
  "retry",
69959
70588
  transport,
69960
- { deliverRecheckedHold: args.deliver_rechecked_hold === true }
70589
+ {
70590
+ deliverRecheckedHold: args.deliver_rechecked_hold === true,
70591
+ legacyDestinationRecovery: args.legacy_destination_recovery
70592
+ }
69961
70593
  );
69962
70594
  }
69963
70595
  if (definition.local === "retry_private_skill_candidate") {
@@ -71058,7 +71690,7 @@ function privateLessonDestinationError(draft, current) {
71058
71690
  function privateLessonDestinationActionRequired(code) {
71059
71691
  switch (code) {
71060
71692
  case "private_lesson_destination_legacy_unbound":
71061
- return "This legacy draft has no authenticated destination binding. Update the client and re-capture the lesson from current safe task context with capture_learning; the retained draft was not sent.";
71693
+ return "This legacy draft has no authenticated destination binding. Request its content-free legacy destination review, then obtain the owner's new approval for that exact draft and organization before local migration. Its retained source stays encrypted and unavailable to the agent; the draft was not sent.";
71062
71694
  case "private_lesson_destination_api_changed":
71063
71695
  return "The API destination differs from the captured destination. Restore the captured API base, then retry the exact retained draft; it will not be sent across API bases.";
71064
71696
  case "private_lesson_destination_credential_changed":
@@ -71070,17 +71702,17 @@ function privateLessonDestinationActionRequired(code) {
71070
71702
  }
71071
71703
  }
71072
71704
  function privateLessonDestinationNextAction(draftId, code) {
71073
- if (code === "private_lesson_destination_legacy_unbound") {
71705
+ if (code === "private_lesson_destination_legacy_unbound" || code === "private_lesson_destination_attestation_mismatch") {
71074
71706
  return {
71075
- tool: "capture_learning",
71076
- action_code: "recapture_legacy_private_lesson_with_destination_binding",
71077
- retained_source_draft_id: draftId,
71078
- retained_source_available_to_agent: false,
71079
- required_input: ["lesson"]
71707
+ tool: "retry_private_lesson_candidate",
71708
+ arguments: {
71709
+ draft_id: draftId,
71710
+ legacy_destination_recovery: { action: "review" }
71711
+ }
71080
71712
  };
71081
71713
  }
71082
71714
  return {
71083
- tool: code === "private_lesson_destination_attestation_mismatch" ? "inspect_private_lesson_outbox" : "retry_private_lesson_candidate",
71715
+ tool: "retry_private_lesson_candidate",
71084
71716
  arguments: { draft_id: draftId }
71085
71717
  };
71086
71718
  }
@@ -71093,7 +71725,10 @@ async function holdPrivateLessonDestination(draft, code) {
71093
71725
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
71094
71726
  }));
71095
71727
  }
71096
- async function submitPrivateLessonDraft(draftId, access, mode, transport, { deliverRecheckedHold = false } = {}) {
71728
+ async function submitPrivateLessonDraft(draftId, access, mode, transport, {
71729
+ deliverRecheckedHold = false,
71730
+ legacyDestinationRecovery
71731
+ } = {}) {
71097
71732
  const allowPolicyRefresh = mode === "retry";
71098
71733
  const currentDestination = privateLessonDestinationForAccess(access);
71099
71734
  const source = await readPrivateLessonSubmissionSource(draftId);
@@ -71125,6 +71760,18 @@ async function submitPrivateLessonDraft(draftId, access, mode, transport, { deli
71125
71760
  status: "already_submitted"
71126
71761
  });
71127
71762
  }
71763
+ if (legacyDestinationRecovery) {
71764
+ return legacyLessonDestinationRecovery(
71765
+ draft,
71766
+ currentDestination,
71767
+ legacyDestinationRecovery,
71768
+ {
71769
+ verifiedOrganizationAudience: async () => (await fetchVerifiedPrivateLessonPolicy(access, transport)).policy.payload.organization_audience_hash,
71770
+ recover: recoverOwnerAttestedLegacyPrivateLessonDestination,
71771
+ readDraft: readPrivateLessonDraft
71772
+ }
71773
+ );
71774
+ }
71128
71775
  if (deliverRecheckedHold && draft.state === "held_safety" && draft.held_reasons.length > 0) {
71129
71776
  try {
71130
71777
  draft = await releaseRecheckedPrivateLessonHold(draft.draft_id);
@@ -73164,9 +73811,9 @@ function formatConnectionDoctorReport(report) {
73164
73811
  `Private lesson action: ${report.private_lesson_automation.action.visibility}`
73165
73812
  );
73166
73813
  if (report.private_lesson_automation.outbox.diagnostic) {
73167
- const diagnostic = report.private_lesson_automation.outbox.diagnostic;
73814
+ const diagnostic2 = report.private_lesson_automation.outbox.diagnostic;
73168
73815
  lines2.push(
73169
- `Private lesson storage: ${diagnostic.reason_code} (${diagnostic.stage}). ${diagnostic.remediation}`
73816
+ `Private lesson storage: ${diagnostic2.reason_code} (${diagnostic2.stage}). ${diagnostic2.remediation}`
73170
73817
  );
73171
73818
  }
73172
73819
  if (report.private_lesson_automation.outbox.deletion_guidance) {