@remembrance-ai/mcp-server 0.2.7 → 0.2.8

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 {
@@ -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"
@@ -30183,7 +30232,7 @@ validateServedToolDefinitionSet(
30183
30232
  );
30184
30233
 
30185
30234
  // src/private-lesson-outbox.ts
30186
- import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes4 } from "node:crypto";
30235
+ import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes5 } from "node:crypto";
30187
30236
  import {
30188
30237
  chmod as chmod2,
30189
30238
  link,
@@ -31561,6 +31610,149 @@ function isLoopError(error) {
31561
31610
  return error instanceof Error && "code" in error && error.code === "ELOOP";
31562
31611
  }
31563
31612
 
31613
+ // src/capture-learning-diagnostics.ts
31614
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
31615
+ import { randomBytes as randomBytes4 } from "node:crypto";
31616
+ var contexts = new AsyncLocalStorage2();
31617
+ var failures = /* @__PURE__ */ new WeakMap();
31618
+ var CaptureLearningReplayError = class extends Error {
31619
+ constructor(code) {
31620
+ super(
31621
+ "This capture identity is already bound to a retained local outcome."
31622
+ );
31623
+ this.code = code;
31624
+ this.name = "CaptureLearningReplayError";
31625
+ }
31626
+ code;
31627
+ };
31628
+ async function withCaptureLearningDiagnostics(operation) {
31629
+ if (contexts.getStore()) return operation();
31630
+ const context = {
31631
+ capture_id: `cap_${randomBytes4(16).toString("hex")}`,
31632
+ correlation_id: `capcorr_${randomBytes4(16).toString("hex")}`,
31633
+ failure_stage: "validation",
31634
+ persistence_outcome: "not_persisted"
31635
+ };
31636
+ return contexts.run(context, async () => {
31637
+ try {
31638
+ return await operation();
31639
+ } catch (error) {
31640
+ const failure = error !== null && (typeof error === "object" || typeof error === "function") ? error : new Error("Private learning capture failed.");
31641
+ failures.set(failure, {
31642
+ ...diagnostic(context),
31643
+ ...preparationConstraintDiagnostic(context, error),
31644
+ ...error instanceof CaptureLearningReplayError ? {
31645
+ code: error.code,
31646
+ 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."
31647
+ } : {}
31648
+ });
31649
+ throw failure;
31650
+ }
31651
+ });
31652
+ }
31653
+ function captureLearningDiagnostic(error) {
31654
+ return error !== null && (typeof error === "object" || typeof error === "function") ? failures.get(error) : void 0;
31655
+ }
31656
+ function captureLearningCurrentDiagnostic() {
31657
+ const context = contexts.getStore();
31658
+ return context ? diagnostic(context) : void 0;
31659
+ }
31660
+ function currentCaptureLearningId() {
31661
+ return contexts.getStore()?.capture_id;
31662
+ }
31663
+ function adoptCaptureLearningId(captureId) {
31664
+ const context = contexts.getStore();
31665
+ if (context && captureId && /^cap_[a-f0-9]{32}$/u.test(captureId)) {
31666
+ context.capture_id = captureId;
31667
+ }
31668
+ }
31669
+ function markCaptureLearningStage(stage) {
31670
+ const context = contexts.getStore();
31671
+ if (context) context.failure_stage = stage;
31672
+ }
31673
+ function markCaptureLearningReplacement(draftId) {
31674
+ const context = contexts.getStore();
31675
+ if (context) context.replacement_of = draftId;
31676
+ }
31677
+ function markCaptureLearningRoute(route) {
31678
+ const context = contexts.getStore();
31679
+ if (context) context.capture_route = route;
31680
+ }
31681
+ function markCaptureLearningPersisting(draftId) {
31682
+ const context = contexts.getStore();
31683
+ if (!context) return;
31684
+ context.failure_stage = "encrypted_persistence";
31685
+ context.persistence_outcome = "unknown";
31686
+ if (draftId) context.reconciliation_draft_id = draftId;
31687
+ }
31688
+ function markCaptureLearningPersisted(draftId) {
31689
+ const context = contexts.getStore();
31690
+ if (!context) return;
31691
+ context.persistence_outcome = "persisted";
31692
+ context.draft_id = draftId;
31693
+ delete context.reconciliation_draft_id;
31694
+ }
31695
+ function markCaptureLearningNotPersisted() {
31696
+ const context = contexts.getStore();
31697
+ if (!context) return;
31698
+ context.persistence_outcome = "not_persisted";
31699
+ delete context.draft_id;
31700
+ delete context.reconciliation_draft_id;
31701
+ }
31702
+ function diagnostic(context) {
31703
+ return {
31704
+ code: `capture_${context.failure_stage}_failed`,
31705
+ ...context.replacement_of ? { replacement_of: context.replacement_of } : { capture_id: context.capture_id },
31706
+ correlation_id: context.correlation_id,
31707
+ failure_stage: context.failure_stage,
31708
+ persistence_outcome: context.persistence_outcome,
31709
+ ...context.capture_route ? { capture_route: context.capture_route } : {},
31710
+ ...context.draft_id ? { draft_id: context.draft_id } : {},
31711
+ ...context.reconciliation_draft_id ? { reconciliation_draft_id: context.reconciliation_draft_id } : context.persistence_outcome === "unknown" && context.capture_route === "private_skill" ? {
31712
+ next_action: {
31713
+ tool: "inspect_private_learning_outbox",
31714
+ arguments: { limit: 50 }
31715
+ }
31716
+ } : {},
31717
+ candidate_sent: false,
31718
+ ...context.draft_id || context.reconciliation_draft_id ? {
31719
+ next_action: {
31720
+ tool: context.capture_route === "private_skill" ? "inspect_private_learning_outbox" : "inspect_private_lesson_outbox",
31721
+ arguments: context.capture_route === "private_skill" ? {
31722
+ limit: 50,
31723
+ private_skill_draft_id: context.draft_id ?? context.reconciliation_draft_id
31724
+ } : {
31725
+ draft_id: context.draft_id ?? context.reconciliation_draft_id
31726
+ }
31727
+ }
31728
+ } : context.replacement_of ? {
31729
+ next_action: {
31730
+ tool: "inspect_private_lesson_outbox",
31731
+ arguments: { draft_id: context.replacement_of }
31732
+ }
31733
+ } : {},
31734
+ 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."
31735
+ };
31736
+ }
31737
+ function preparationConstraintDiagnostic(context, error) {
31738
+ if (context.failure_stage !== "preparation" || !(error instanceof ZodError))
31739
+ return {};
31740
+ if (!error.issues.some(
31741
+ (issue) => issue.path[0] === "evidence_hashes" && issue.code === "invalid_string" && issue.validation === "regex"
31742
+ ))
31743
+ return {};
31744
+ return {
31745
+ validation_issues: [
31746
+ {
31747
+ path: "$.lesson.evidence_hashes[]",
31748
+ code: "invalid_string",
31749
+ constraint: "^sha256:[a-f0-9]{64}$"
31750
+ }
31751
+ ],
31752
+ remediation: "Use sha256: followed by exactly 64 lowercase hexadecimal characters; omit evidence_hashes when no digest exists."
31753
+ };
31754
+ }
31755
+
31564
31756
  // src/private-lesson-outbox.ts
31565
31757
  var PRIVATE_LESSON_OUTBOX_VERSION = "private-lesson-outbox-v1";
31566
31758
  var PRIVATE_LESSON_OUTBOX_MAX_BYTES = 64 * 1024 * 1024;
@@ -31666,18 +31858,78 @@ async function releaseRecheckedPrivateLessonHold(draftId, options = {}) {
31666
31858
  });
31667
31859
  }
31668
31860
  async function queuePreparedPrivateLesson(prepared, policy, options = {}) {
31861
+ const draftId = options.captureId ? privateLessonCaptureDraftId(options.captureId) : createPublicId("pld");
31669
31862
  const outbox = await readyOutbox(options);
31670
31863
  const draft = newPrivateLessonDraft(
31671
31864
  prepared,
31672
- createPublicId("pld"),
31865
+ draftId,
31673
31866
  policy,
31674
31867
  options.destination ?? null,
31675
- options.now ?? /* @__PURE__ */ new Date()
31868
+ options.now ?? /* @__PURE__ */ new Date(),
31869
+ options.captureId !== void 0
31676
31870
  );
31677
- await writeDraft(draft, outbox, false);
31678
- return draft;
31871
+ return withPrivateLessonOutboxLock(outbox.directory, async () => {
31872
+ if (options.captureId) {
31873
+ markCaptureLearningPersisting(draftId);
31874
+ const unresolved = await reconcilePrivateLessonTemporaryWrites(
31875
+ outbox.directory,
31876
+ outbox.encryption
31877
+ );
31878
+ if (unresolved.has(draftId)) {
31879
+ throw new CaptureLearningReplayError("capture_reconciliation_required");
31880
+ }
31881
+ if ((await privateLessonQuarantineEntriesForDraft(
31882
+ outbox.directory,
31883
+ draftId
31884
+ )).length > 0) {
31885
+ throw new CaptureLearningReplayError("capture_reconciliation_required");
31886
+ }
31887
+ if (existsSync2(tombstonePath(outbox.directory, draftId))) {
31888
+ throw new CaptureLearningReplayError("capture_id_deleted");
31889
+ }
31890
+ await assertNotReplacedUnlocked(outbox.directory, draftId);
31891
+ const completion = existsSync2(
31892
+ submittedRecordPath(outbox.directory, draftId)
31893
+ ) ? await readPrivateLessonSubmittedRecord(draftId, {
31894
+ ...options,
31895
+ encryption: outbox.encryption,
31896
+ outboxDirectory: outbox.directory
31897
+ }) : null;
31898
+ if (completion) {
31899
+ markCaptureLearningPersisted(draftId);
31900
+ throw new CaptureLearningReplayError("capture_id_already_submitted");
31901
+ }
31902
+ if (existsSync2(draftPath(outbox.directory, draftId))) {
31903
+ const existing = await readPrivateLessonDraft(draftId, {
31904
+ ...options,
31905
+ encryption: outbox.encryption,
31906
+ outboxDirectory: outbox.directory
31907
+ });
31908
+ markCaptureLearningPersisted(draftId);
31909
+ if (existing.payload_digest !== draft.payload_digest || existing.redactor_digest !== draft.redactor_digest) {
31910
+ throw new CaptureLearningReplayError("capture_id_payload_mismatch");
31911
+ }
31912
+ if (canonicalJson(existing.destination_binding) !== canonicalJson(draft.destination_binding)) {
31913
+ throw new CaptureLearningReplayError(
31914
+ "capture_id_destination_mismatch"
31915
+ );
31916
+ }
31917
+ return existing;
31918
+ }
31919
+ markCaptureLearningNotPersisted();
31920
+ }
31921
+ await writeDraft(draft, outbox, false);
31922
+ markCaptureLearningPersisted(draftId);
31923
+ return draft;
31924
+ });
31925
+ }
31926
+ function privateLessonCaptureDraftId(captureId) {
31927
+ if (!/^cap_[a-f0-9]{32}$/u.test(captureId)) {
31928
+ throw new Error("Private lesson capture identity is invalid.");
31929
+ }
31930
+ return `pld_${hashValue(`private-lesson-capture-v1:${captureId}`).replace(/^sha256:/u, "")}`;
31679
31931
  }
31680
- function newPrivateLessonDraft(prepared, draftId, policy, destination, now) {
31932
+ function newPrivateLessonDraft(prepared, draftId, policy, destination, now, stableCaptureIdentity = false) {
31681
31933
  const createdAt = now.toISOString();
31682
31934
  const state = prepared.status === "held_safety" ? "held_safety" : policy ? "ready" : "awaiting_authorization";
31683
31935
  return {
@@ -31693,10 +31945,9 @@ function newPrivateLessonDraft(prepared, draftId, policy, destination, now) {
31693
31945
  policy,
31694
31946
  destination_binding: destination ? parsePrivateLessonDestination(destination) : null,
31695
31947
  idempotency_key: `private-lesson-${hashValue(
31696
- canonicalJson({
31697
- draft_id: draftId,
31698
- payload_digest: prepared.payload_digest
31699
- })
31948
+ canonicalJson(
31949
+ stableCaptureIdentity ? { draft_id: draftId } : { draft_id: draftId, payload_digest: prepared.payload_digest }
31950
+ )
31700
31951
  ).replace(/^sha256:/, "")}`,
31701
31952
  attempts: 0,
31702
31953
  next_retry_at: null,
@@ -31800,6 +32051,14 @@ async function queuePrivateLessonReplacement(replacementOf, prepared, options =
31800
32051
  const attempts = original.replacement_attempts ?? [];
31801
32052
  const digest2 = prepared.payload_digest;
31802
32053
  const draftId = privateLessonReplacementDraftId(replacementOf, digest2);
32054
+ markCaptureLearningPersisting(draftId);
32055
+ const unresolved = await reconcilePrivateLessonTemporaryWrites(
32056
+ directory,
32057
+ outbox.encryption
32058
+ );
32059
+ if (unresolved.has(draftId) || (await privateLessonQuarantineEntriesForDraft(directory, draftId)).length > 0) {
32060
+ throw new CaptureLearningReplayError("capture_reconciliation_required");
32061
+ }
31803
32062
  const replay = attempts.includes(digest2);
31804
32063
  const used = replay ? attempts.length : attempts.length + 1;
31805
32064
  if (!replay && privateLessonCapturedForOtherDestination(original, options.destination)) {
@@ -31830,11 +32089,13 @@ async function queuePrivateLessonReplacement(replacementOf, prepared, options =
31830
32089
  throw refuse("replacement_deleted", used, draftId);
31831
32090
  }
31832
32091
  if (existsSync2(draftPath(directory, draftId))) {
32092
+ const existing = await readPrivateLessonDraft(draftId, {
32093
+ ...read2,
32094
+ encryption: outbox.encryption
32095
+ });
32096
+ markCaptureLearningPersisted(draftId);
31833
32097
  return {
31834
- draft: await readPrivateLessonDraft(draftId, {
31835
- ...read2,
31836
- encryption: outbox.encryption
31837
- }),
32098
+ draft: existing,
31838
32099
  attempts_remaining: PRIVATE_LESSON_REPLACEMENT_MAX_ATTEMPTS - used,
31839
32100
  replayed: true
31840
32101
  };
@@ -31906,10 +32167,15 @@ async function readPrivateLessonDraft(draftId, options = {}) {
31906
32167
  assertDraftId(draftId);
31907
32168
  const outbox = await readyOutbox(options, false);
31908
32169
  return withPrivateLessonOutboxLock(outbox.directory, async () => {
31909
- await reconcilePrivateLessonTemporaryWrites(
32170
+ const unresolved = await reconcilePrivateLessonTemporaryWrites(
31910
32171
  outbox.directory,
31911
32172
  outbox.encryption
31912
32173
  );
32174
+ const unresolvedError = unresolved.get(draftId);
32175
+ if (unresolvedError) throw unresolvedError;
32176
+ if (!existsSync2(draftPath(outbox.directory, draftId)) && (await privateLessonQuarantineEntriesForDraft(outbox.directory, draftId)).length > 0) {
32177
+ throw new PrivateLessonDraftUnavailableError(draftId, "corrupt");
32178
+ }
31913
32179
  if (existsSync2(tombstonePath(outbox.directory, draftId))) {
31914
32180
  throw new PrivateLessonDraftUnavailableError(draftId, "deleted");
31915
32181
  }
@@ -32105,6 +32371,67 @@ async function updatePrivateLessonDraft(draftId, update, options = {}) {
32105
32371
  return next;
32106
32372
  });
32107
32373
  }
32374
+ function ownerAttestedLegacyPrivateLessonRecoveryEligible(draft) {
32375
+ const legacyUnbound = draft.destination_binding === null && draft.last_error_code === "private_lesson_destination_legacy_unbound" && (draft.state === "held_validation" || draft.state === "retry_scheduled");
32376
+ const heldForOtherOrganization = draft.attested_organization_audience_hash !== void 0 && draft.last_error_code === "private_lesson_destination_attestation_mismatch" && draft.state === "held_validation";
32377
+ 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;
32378
+ }
32379
+ async function recoverOwnerAttestedLegacyPrivateLessonDestination(input, options = {}) {
32380
+ assertDraftId(input.draft_id);
32381
+ 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") {
32382
+ throw new Error("Explicit owner-attested legacy recovery authorization is required.");
32383
+ }
32384
+ const destination = parsePrivateLessonDestination(input.destination);
32385
+ const outbox = await readyOutbox(options, false);
32386
+ return withPrivateLessonOutboxLock(outbox.directory, async () => {
32387
+ if (existsSync2(tombstonePath(outbox.directory, input.draft_id)) || existsSync2(submittedRecordPath(outbox.directory, input.draft_id))) {
32388
+ throw new Error("Legacy recovery requires an unresolved retained draft.");
32389
+ }
32390
+ const path = draftPath(outbox.directory, input.draft_id);
32391
+ await assertRegularPrivateFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES);
32392
+ const serialized = await readBoundedFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES);
32393
+ const envelope = parseEnvelope(serialized, input.draft_id);
32394
+ const current = await decryptDraft(envelope, outbox.encryption);
32395
+ if (!ownerAttestedLegacyPrivateLessonRecoveryEligible(current) || current.payload_digest !== input.expected_payload_digest) {
32396
+ throw new Error("Selected draft does not match the owner-attested legacy recovery scope.");
32397
+ }
32398
+ const now = (options.now ?? /* @__PURE__ */ new Date()).toISOString();
32399
+ const next = {
32400
+ ...current,
32401
+ destination_binding: destination,
32402
+ attested_organization_audience_hash: input.organization_audience_hash,
32403
+ state: "retry_scheduled",
32404
+ next_retry_at: now,
32405
+ last_error_code: null,
32406
+ updated_at: now
32407
+ };
32408
+ const encryption = {
32409
+ key: await readPrivateLessonOutboxKey(outbox.encryption, envelope.encryption.key_source),
32410
+ source: envelope.encryption.key_source
32411
+ };
32412
+ if (!input.dry_run) await writeDraft(next, { ...outbox, encryption }, true);
32413
+ return {
32414
+ draft_id: current.draft_id,
32415
+ payload_digest: current.payload_digest,
32416
+ original_identity_sha256: hashValue(canonicalJson({
32417
+ draft_id: current.draft_id,
32418
+ canonical_payload: current.canonical_payload,
32419
+ payload_digest: current.payload_digest,
32420
+ redaction_version: current.redaction_version,
32421
+ redactor_digest: current.redactor_digest,
32422
+ idempotency_key: current.idempotency_key,
32423
+ policy: current.policy,
32424
+ created_at: current.created_at
32425
+ })),
32426
+ before_envelope_sha256: hashValue(serialized),
32427
+ after_envelope_sha256: input.dry_run ? null : hashValue(await readBoundedFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES)),
32428
+ owner_attestation_sha256: input.owner_attestation_sha256,
32429
+ organization_audience_hash: input.organization_audience_hash,
32430
+ status: input.dry_run ? "destination_recovery_preflight" : "destination_recovered",
32431
+ candidate_sent: false
32432
+ };
32433
+ });
32434
+ }
32108
32435
  async function completePrivateLessonSubmission(draftId, input, options = {}) {
32109
32436
  assertDraftId(draftId);
32110
32437
  const outbox = await readyOutbox(options);
@@ -32631,7 +32958,7 @@ async function inspectPrivateLessonOutboxHealth(options = {}) {
32631
32958
  const env = options.env ?? process.env;
32632
32959
  const directory = options.outboxDirectory ?? privateLessonOutboxDirectory(env, options.homeDirectory);
32633
32960
  let encryption = options.encryption ?? null;
32634
- let diagnostic;
32961
+ let diagnostic2;
32635
32962
  if (!encryption) {
32636
32963
  try {
32637
32964
  encryption = await readExistingPrivateLessonOutboxEncryption(
@@ -32639,21 +32966,21 @@ async function inspectPrivateLessonOutboxHealth(options = {}) {
32639
32966
  options
32640
32967
  );
32641
32968
  } catch (error) {
32642
- diagnostic = error instanceof PrivateOutboxStorageError ? error.diagnostic() : privateOutboxStorageError(error, "fallback_key_read").diagnostic();
32969
+ diagnostic2 = error instanceof PrivateOutboxStorageError ? error.diagnostic() : privateOutboxStorageError(error, "fallback_key_read").diagnostic();
32643
32970
  }
32644
32971
  }
32645
32972
  const inventory = retainedKeyInventory({
32646
32973
  ...options,
32647
32974
  outboxDirectory: directory
32648
32975
  });
32649
- if (!encryption && !diagnostic) {
32650
- diagnostic = privateLearningKeyBootstrapHold(
32976
+ if (!encryption && !diagnostic2) {
32977
+ diagnostic2 = privateLearningKeyBootstrapHold(
32651
32978
  inventory,
32652
32979
  "confirmed_missing",
32653
32980
  "fallback_key_read"
32654
32981
  )?.diagnostic();
32655
32982
  }
32656
- const encryptionReady = diagnostic ? diagnostic.reason_code === "outbox_key_missing" ? false : null : encryption !== null;
32983
+ const encryptionReady = diagnostic2 ? diagnostic2.reason_code === "outbox_key_missing" ? false : null : encryption !== null;
32657
32984
  const keyFileState = () => privateLessonFallbackKeyState(
32658
32985
  { ...options, outboxDirectory: directory },
32659
32986
  encryption?.source,
@@ -32664,8 +32991,8 @@ async function inspectPrivateLessonOutboxHealth(options = {}) {
32664
32991
  return {
32665
32992
  storage_initialized: false,
32666
32993
  encryption_ready: encryptionReady,
32667
- encryption_source: diagnostic ? null : encryption?.source ?? "uninitialized",
32668
- ...diagnostic ? { diagnostic } : {},
32994
+ encryption_source: diagnostic2 ? null : encryption?.source ?? "uninitialized",
32995
+ ...diagnostic2 ? { diagnostic: diagnostic2 } : {},
32669
32996
  ...await keyFileState(),
32670
32997
  total_bytes: 0,
32671
32998
  ceiling_bytes: ceilingBytes2,
@@ -32780,8 +33107,8 @@ async function inspectPrivateLessonOutboxHealth(options = {}) {
32780
33107
  return {
32781
33108
  storage_initialized: true,
32782
33109
  encryption_ready: encryptionReady,
32783
- encryption_source: diagnostic ? null : "uninitialized",
32784
- ...diagnostic ? { diagnostic } : {},
33110
+ encryption_source: diagnostic2 ? null : "uninitialized",
33111
+ ...diagnostic2 ? { diagnostic: diagnostic2 } : {},
32785
33112
  ...keyFile,
32786
33113
  total_bytes: totalBytes,
32787
33114
  ceiling_bytes: ceilingBytes,
@@ -32940,7 +33267,7 @@ async function resolveFallbackOutboxEncryption(options) {
32940
33267
  encoded = await readConcurrentPrivateLessonFallbackKey(path);
32941
33268
  } catch (error) {
32942
33269
  if (!isMissingError2(error)) throw error;
32943
- encoded = randomBytes4(32).toString("base64url");
33270
+ encoded = randomBytes5(32).toString("base64url");
32944
33271
  try {
32945
33272
  await atomicWritePrivate(path, `${encoded}
32946
33273
  `);
@@ -33187,7 +33514,7 @@ async function writeDraftUnlocked(draft, outbox, replace, _currentOutboxBytes, a
33187
33514
  if (plaintext.length > PRIVATE_LESSON_DRAFT_MAX_BYTES) {
33188
33515
  throw new Error("Private lesson draft exceeds its local size limit.");
33189
33516
  }
33190
- const nonce = randomBytes4(12);
33517
+ const nonce = randomBytes5(12);
33191
33518
  const aad = Buffer.from(
33192
33519
  canonicalJson({
33193
33520
  version: "private-lesson-outbox-envelope-v1",
@@ -33245,7 +33572,28 @@ async function writeDraftUnlocked(draft, outbox, replace, _currentOutboxBytes, a
33245
33572
  if (replace) {
33246
33573
  await atomicReplacePrivate(path, serialized);
33247
33574
  } else {
33248
- await atomicCreatePrivateLessonEntry(path, serialized);
33575
+ markCaptureLearningPersisting(validated.draft_id);
33576
+ try {
33577
+ await atomicCreatePrivateLessonEntry(path, serialized);
33578
+ } catch (error) {
33579
+ try {
33580
+ await assertRegularPrivateFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES);
33581
+ const retained = await decryptDraft(
33582
+ parseEnvelope(
33583
+ await readBoundedFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES),
33584
+ validated.draft_id
33585
+ ),
33586
+ outbox.encryption,
33587
+ true
33588
+ );
33589
+ if (retained.payload_digest === validated.payload_digest) {
33590
+ markCaptureLearningPersisted(validated.draft_id);
33591
+ }
33592
+ } catch {
33593
+ }
33594
+ throw error;
33595
+ }
33596
+ markCaptureLearningPersisted(validated.draft_id);
33249
33597
  }
33250
33598
  }
33251
33599
  async function decryptDraft(envelope, encryption, allowUnsupportedProfile = false) {
@@ -33861,13 +34209,13 @@ async function appendPrivateLessonQuarantineRecoveryItems(directory, items) {
33861
34209
  }
33862
34210
  function privateLessonRecoveryItem(draftId, reasonCode, storageError) {
33863
34211
  if (reasonCode === "undecryptable_entry") {
33864
- const diagnostic = storageError?.diagnostic();
34212
+ const diagnostic2 = storageError?.diagnostic();
33865
34213
  return {
33866
34214
  lane: "private_lesson",
33867
34215
  draft_id: draftId,
33868
34216
  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 } : {}
34217
+ remediation: diagnostic2?.remediation ?? "Restore access to the original encryption key, then inspect the retained draft again. Do not delete or regenerate it.",
34218
+ ...diagnostic2 ? { diagnostic: diagnostic2 } : {}
33871
34219
  };
33872
34220
  }
33873
34221
  if (reasonCode === "held_safety_recovery_required") {
@@ -33899,6 +34247,7 @@ function privateLessonRecoveryItem(draftId, reasonCode, storageError) {
33899
34247
  };
33900
34248
  }
33901
34249
  async function reconcilePrivateLessonTemporaryWrites(directory, encryption) {
34250
+ const unresolved = /* @__PURE__ */ new Map();
33902
34251
  const groups = /* @__PURE__ */ new Map();
33903
34252
  for (const entry of await readdir(directory, { withFileTypes: true })) {
33904
34253
  if (/^\.[a-f0-9]{24}\.(?:capacity|replaced)\.tmp$/u.test(entry.name) && entry.isFile()) {
@@ -33919,9 +34268,15 @@ async function reconcilePrivateLessonTemporaryWrites(directory, encryption) {
33919
34268
  const envelope = parseEnvelope(value, draftId);
33920
34269
  await decryptDraft(envelope, encryption, true);
33921
34270
  } catch (error) {
33922
- if (isPrivateOutboxKeyAccessError(error)) continue;
34271
+ if (isPrivateOutboxKeyAccessError(error)) {
34272
+ if (draftId) unresolved.set(draftId, error);
34273
+ continue;
34274
+ }
33923
34275
  if (error instanceof PrivateOutboxStorageError) throw error;
33924
- if (error instanceof PrivateOutboxDecryptionError) continue;
34276
+ if (error instanceof PrivateOutboxDecryptionError) {
34277
+ if (draftId) unresolved.set(draftId, error);
34278
+ continue;
34279
+ }
33925
34280
  const recoveryId = derivedPrivateLessonRecoveryId(entry.name);
33926
34281
  await quarantinePrivateLessonTemporary(
33927
34282
  directory,
@@ -33975,6 +34330,11 @@ async function reconcilePrivateLessonTemporaryWrites(directory, encryption) {
33975
34330
  await unlink2(join3(directory, duplicate.name));
33976
34331
  }
33977
34332
  } else {
34333
+ const draftId = target.slice(0, -".lesson.json".length);
34334
+ unresolved.set(
34335
+ draftId,
34336
+ new PrivateLessonDraftUnavailableError(draftId, "corrupt")
34337
+ );
33978
34338
  for (const temporary of temporaryValues) {
33979
34339
  await quarantinePrivateLessonTemporary(
33980
34340
  directory,
@@ -33985,6 +34345,7 @@ async function reconcilePrivateLessonTemporaryWrites(directory, encryption) {
33985
34345
  }
33986
34346
  }
33987
34347
  }
34348
+ return unresolved;
33988
34349
  }
33989
34350
  async function validatePrivateLessonCanonicalPath(path, name, encryption) {
33990
34351
  const draftId = name.match(/^(pld_[A-Za-z0-9_-]{8,96})/u)?.[1];
@@ -34046,7 +34407,7 @@ async function quarantinePrivateLessonTemporary(directory, draftId, temporaryNam
34046
34407
  join3(directory, temporaryName),
34047
34408
  join3(
34048
34409
  quarantine,
34049
- `${draftId}.${reason}.${randomBytes4(8).toString("hex")}.retained`
34410
+ `${draftId}.${reason}.${randomBytes5(8).toString("hex")}.retained`
34050
34411
  )
34051
34412
  );
34052
34413
  }
@@ -34092,7 +34453,7 @@ async function recordPrivateLessonCapacityRejection(directory, rejectedCaptureBy
34092
34453
  const path = join3(directory, PRIVATE_LESSON_CAPACITY_STATE_FILE);
34093
34454
  const temporary = join3(
34094
34455
  directory,
34095
- `.${randomBytes4(12).toString("hex")}.capacity.tmp`
34456
+ `.${randomBytes5(12).toString("hex")}.capacity.tmp`
34096
34457
  );
34097
34458
  const encoded = `${canonicalJson({
34098
34459
  version: "private-outbox-capacity-v1",
@@ -34178,7 +34539,7 @@ async function atomicWritePrivate(path, data) {
34178
34539
  async function atomicCreatePrivateLessonEntry(path, data, temporarySuffix = ".tmp") {
34179
34540
  const temporary = join3(
34180
34541
  dirname3(path),
34181
- `.${randomBytes4(12).toString("hex")}${temporarySuffix}`
34542
+ `.${randomBytes5(12).toString("hex")}${temporarySuffix}`
34182
34543
  );
34183
34544
  try {
34184
34545
  await atomicWritePrivate(temporary, data);
@@ -34194,7 +34555,7 @@ async function atomicReplacePrivate(path, data) {
34194
34555
  await assertRegularPrivateFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES);
34195
34556
  const temporary = join3(
34196
34557
  dirname3(path),
34197
- `.${randomBytes4(12).toString("hex")}.tmp`
34558
+ `.${randomBytes5(12).toString("hex")}.tmp`
34198
34559
  );
34199
34560
  try {
34200
34561
  await atomicWritePrivate(temporary, data);
@@ -34989,18 +35350,18 @@ var require_commonmark = __commonJS({
34989
35350
  strIdx += 1;
34990
35351
  if (str.charCodeAt(strIdx) === 35) {
34991
35352
  var start = strIdx + 1;
34992
- var base = 10;
35353
+ var base2 = 10;
34993
35354
  var cp = str.charCodeAt(start);
34994
35355
  if ((cp | 32) === 120) {
34995
- base = 16;
35356
+ base2 = 16;
34996
35357
  strIdx += 1;
34997
35358
  start += 1;
34998
35359
  }
34999
- while ((cp = str.charCodeAt(++strIdx)) >= 48 && cp <= 57 || base === 16 && (cp | 32) >= 97 && (cp | 32) <= 102)
35360
+ while ((cp = str.charCodeAt(++strIdx)) >= 48 && cp <= 57 || base2 === 16 && (cp | 32) >= 97 && (cp | 32) <= 102)
35000
35361
  ;
35001
35362
  if (start !== strIdx) {
35002
35363
  var entity = str.substring(start, strIdx);
35003
- var parsed = parseInt(entity, base);
35364
+ var parsed = parseInt(entity, base2);
35004
35365
  if (str.charCodeAt(strIdx) === 59) {
35005
35366
  strIdx += 1;
35006
35367
  } else if (strict) {
@@ -54823,15 +55184,15 @@ var Inst = class Inst2 {
54823
55184
  }
54824
55185
  return false;
54825
55186
  }
54826
- let base = 0;
55187
+ let base2 = 0;
54827
55188
  let n = len >> 1;
54828
55189
  while (n > 1) {
54829
55190
  const half = n >> 1;
54830
- base += this.runes[base + half << 1] <= r ? half : 0;
55191
+ base2 += this.runes[base2 + half << 1] <= r ? half : 0;
54831
55192
  n -= half;
54832
55193
  }
54833
- base += this.runes[base << 1] <= r ? 1 : 0;
54834
- const m = base - 1;
55194
+ base2 += this.runes[base2 << 1] <= r ? 1 : 0;
55195
+ const m = base2 - 1;
54835
55196
  return m >= 0 && r <= this.runes[m << 1 | 1];
54836
55197
  }
54837
55198
  matchRunePos(r) {
@@ -54849,15 +55210,15 @@ var Inst = class Inst2 {
54849
55210
  }
54850
55211
  return -1;
54851
55212
  }
54852
- let base = 0;
55213
+ let base2 = 0;
54853
55214
  let n = len >> 1;
54854
55215
  while (n > 1) {
54855
55216
  const half = n >> 1;
54856
- base += this.runes[base + half << 1] <= r ? half : 0;
55217
+ base2 += this.runes[base2 + half << 1] <= r ? half : 0;
54857
55218
  n -= half;
54858
55219
  }
54859
- base += this.runes[base << 1] <= r ? 1 : 0;
54860
- const m = base - 1;
55220
+ base2 += this.runes[base2 << 1] <= r ? 1 : 0;
55221
+ const m = base2 - 1;
54861
55222
  return m >= 0 && r <= this.runes[m << 1 | 1] ? m : -1;
54862
55223
  }
54863
55224
  /**
@@ -62604,7 +62965,7 @@ function inspectPrivateSkillCandidate(candidate) {
62604
62965
  }
62605
62966
 
62606
62967
  // src/private-skill-outbox.ts
62607
- import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes5 } from "node:crypto";
62968
+ import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes6 } from "node:crypto";
62608
62969
  import {
62609
62970
  chmod as chmod3,
62610
62971
  lstat as lstat3,
@@ -64831,7 +65192,7 @@ async function ensurePrivateDirectory(path) {
64831
65192
  async function writePrivateSkillDraft(draft, directory, encryption, env = process.env) {
64832
65193
  const parsed = validatePrivateSkillDraft(draft);
64833
65194
  const metadata = envelopeMetadata(parsed);
64834
- const nonce = randomBytes5(12);
65195
+ const nonce = randomBytes6(12);
64835
65196
  const cipher = createCipheriv3("aes-256-gcm", encryption.key, nonce);
64836
65197
  cipher.setAAD(Buffer.from(canonicalJson(metadata)));
64837
65198
  const ciphertext = Buffer.concat([
@@ -65150,12 +65511,12 @@ function parseRetainedNativeContexts(value) {
65150
65511
  if (value === void 0) return [];
65151
65512
  if (!Array.isArray(value))
65152
65513
  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)
65514
+ const contexts2 = value.map(parsePrivateSkillNativeContext);
65515
+ const sources = new Set(contexts2.map((context) => context.source_digest));
65516
+ const contents = new Set(contexts2.map((context) => context.context_digest));
65517
+ if (sources.size !== contexts2.length || contents.size !== contexts2.length)
65157
65518
  throw new Error("Private skill native context lineage is duplicated.");
65158
- return contexts;
65519
+ return contexts2;
65159
65520
  }
65160
65521
  function parsePrivateSkillReformulationAttempts(value, draftId, originalCandidateDigest) {
65161
65522
  if (value === void 0) return [];
@@ -65611,7 +65972,7 @@ function privateSkillInspectorRefreshAllowed(draft) {
65611
65972
  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
65973
  }
65613
65974
  function envelopeMetadataFromEnvelope(envelope) {
65614
- const base = {
65975
+ const base2 = {
65615
65976
  version: envelope.version,
65616
65977
  draft_id: envelope.draft_id,
65617
65978
  state: envelope.state,
@@ -65621,7 +65982,7 @@ function envelopeMetadataFromEnvelope(envelope) {
65621
65982
  updated_at: envelope.updated_at
65622
65983
  };
65623
65984
  return hasEnvelopeReformulationMetadata(envelope) ? {
65624
- ...base,
65985
+ ...base2,
65625
65986
  reformulation_available: envelope.reformulation_available,
65626
65987
  reformulation_reason: envelope.reformulation_reason,
65627
65988
  reformulation_attempt_count: envelope.reformulation_attempt_count,
@@ -65631,7 +65992,7 @@ function envelopeMetadataFromEnvelope(envelope) {
65631
65992
  ...envelope.inspector_digest === void 0 ? {} : { inspector_digest: envelope.inspector_digest },
65632
65993
  ...envelope.native_context_pending === void 0 ? {} : { native_context_pending: envelope.native_context_pending },
65633
65994
  ...envelope.next_action === void 0 ? {} : { next_action: envelope.next_action }
65634
- } : base;
65995
+ } : base2;
65635
65996
  }
65636
65997
  function parseEnvelope2(value) {
65637
65998
  const parsed = JSON.parse(value);
@@ -65957,13 +66318,13 @@ async function privateSkillRecoveryItems(options = {}) {
65957
66318
  }
65958
66319
  function privateSkillRecoveryItem(draftId, reasonCode, storageError) {
65959
66320
  if (reasonCode === "undecryptable_entry") {
65960
- const diagnostic = storageError?.diagnostic();
66321
+ const diagnostic2 = storageError?.diagnostic();
65961
66322
  return {
65962
66323
  lane: "private_skill",
65963
66324
  draft_id: draftId,
65964
66325
  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 } : {}
66326
+ remediation: diagnostic2?.remediation ?? "Restore access to the original encryption key, then inspect the retained draft again. Do not delete or regenerate it.",
66327
+ ...diagnostic2 ? { diagnostic: diagnostic2 } : {}
65967
66328
  };
65968
66329
  }
65969
66330
  return {
@@ -66096,7 +66457,7 @@ async function quarantinePrivateSkillTemporary(directory, target, temporaryName,
66096
66457
  join4(directory, temporaryName),
66097
66458
  join4(
66098
66459
  quarantine,
66099
- `${target.replace(/\.json$/u, "")}.${reason}.${randomBytes5(8).toString("hex")}.retained`
66460
+ `${target.replace(/\.json$/u, "")}.${reason}.${randomBytes6(8).toString("hex")}.retained`
66100
66461
  )
66101
66462
  );
66102
66463
  }
@@ -66230,7 +66591,7 @@ async function atomicWritePrivateJson(path, value) {
66230
66591
  }
66231
66592
  async function atomicWritePrivateText(path, value) {
66232
66593
  await ensurePrivateDirectory(dirname4(path));
66233
- const temporary = `${path}.${process.pid}.${randomBytes5(8).toString("hex")}.tmp`;
66594
+ const temporary = `${path}.${process.pid}.${randomBytes6(8).toString("hex")}.tmp`;
66234
66595
  let handle = null;
66235
66596
  try {
66236
66597
  handle = await open3(temporary, "wx", 384);
@@ -66750,7 +67111,9 @@ async function executeLocalOnlyTool(name, payload, context) {
66750
67111
  case "get_pending_action_payload":
66751
67112
  return LOCAL_ONLY_HANDLERS.get_pending_action_payload(payload, context);
66752
67113
  case "capture_learning":
66753
- return LOCAL_ONLY_HANDLERS.capture_learning(payload, context);
67114
+ return withCaptureLearningDiagnostics(
67115
+ async () => LOCAL_ONLY_HANDLERS.capture_learning(payload, context)
67116
+ );
66754
67117
  case "inspect_private_learning_outbox":
66755
67118
  return LOCAL_ONLY_HANDLERS.inspect_private_learning_outbox(
66756
67119
  payload,
@@ -66811,7 +67174,8 @@ function acknowledgeFeedbackDenialLocally(input, persistence) {
66811
67174
  };
66812
67175
  }
66813
67176
  }
66814
- async function preparePrivateLessonDraft(input, persistence, destination, tool, replacementOf) {
67177
+ async function preparePrivateLessonDraft(input, persistence, destination, tool, replacementOf, captureId) {
67178
+ markCaptureLearningStage("preparation");
66815
67179
  const prepared = preparePrivateLessonCandidate(input, { tool });
66816
67180
  if (replacementOf) {
66817
67181
  return preparePrivateLessonReplacement(
@@ -66822,26 +67186,37 @@ async function preparePrivateLessonDraft(input, persistence, destination, tool,
66822
67186
  destination
66823
67187
  );
66824
67188
  }
67189
+ markCaptureLearningStage("encrypted_persistence");
67190
+ if (captureId) {
67191
+ markCaptureLearningPersisting(privateLessonCaptureDraftId(captureId));
67192
+ }
66825
67193
  const draft = await persistence.queuePreparedPrivateLesson(
66826
67194
  prepared,
66827
- destination
67195
+ destination,
67196
+ captureId
66828
67197
  );
67198
+ markCaptureLearningPersisted(draft.draft_id);
67199
+ markCaptureLearningStage("response");
66829
67200
  return privateLessonDraftActionResult(draft, destination, {
66830
- next_action: prepared.status === "ready" || prepared.status === "held_safety" && privateLessonHealthReportingEnabled() ? {
67201
+ next_action: prepared.status === "ready" && (draft.state === "ready" || draft.state === "awaiting_authorization") || prepared.status === "held_safety" && draft.state === "held_safety" && privateLessonHealthReportingEnabled() ? {
66831
67202
  tool: "submit_private_lesson_candidate",
66832
67203
  arguments: { draft_id: draft.draft_id }
66833
- } : null,
67204
+ } : privateLessonNextAction(draft),
66834
67205
  // Where the lesson holds, without its text, for a replacement.
66835
67206
  ...prepared.status === "held_safety" ? privateLessonFindings(input) : {}
66836
67207
  });
66837
67208
  }
66838
67209
  async function preparePrivateLessonReplacement(input, prepared, replacementOf, persistence, destination) {
67210
+ markCaptureLearningStage("encrypted_persistence");
67211
+ markCaptureLearningPersisting();
66839
67212
  try {
66840
67213
  const { draft, attempts_remaining, replayed } = await persistence.queuePrivateLessonReplacement(
66841
67214
  replacementOf,
66842
67215
  prepared,
66843
67216
  destination
66844
67217
  );
67218
+ markCaptureLearningPersisted(draft.draft_id);
67219
+ markCaptureLearningStage("response");
66845
67220
  return privateLessonDraftActionResult(draft, destination, {
66846
67221
  replacement_attempts_remaining: attempts_remaining,
66847
67222
  replayed,
@@ -66856,8 +67231,11 @@ async function preparePrivateLessonReplacement(input, prepared, replacementOf, p
66856
67231
  if (!(error instanceof PrivateLessonReplacementRefusedError) || error.reason !== "replacement_held") {
66857
67232
  throw error;
66858
67233
  }
67234
+ markCaptureLearningNotPersisted();
67235
+ markCaptureLearningStage("response");
66859
67236
  return {
66860
67237
  status: "not_stored",
67238
+ persistence_outcome: "not_persisted",
66861
67239
  ...error.diagnostic(),
66862
67240
  held_reasons: prepared.held_reasons,
66863
67241
  ...privateLessonFindings(input),
@@ -66871,7 +67249,12 @@ async function preparePrivateLessonReplacement(input, prepared, replacementOf, p
66871
67249
  }
66872
67250
  async function captureLearning(input, persistence, lessonDestination, skillDestination) {
66873
67251
  const parsed = captureLearningInputSchema.parse(input);
67252
+ adoptCaptureLearningId(parsed.capture_id);
66874
67253
  const route = captureLearningRoute(parsed);
67254
+ markCaptureLearningRoute(route);
67255
+ if (route === "private_lesson" && parsed.replacement_of) {
67256
+ markCaptureLearningReplacement(parsed.replacement_of.draft_id);
67257
+ }
66875
67258
  if (route === "preference") {
66876
67259
  return {
66877
67260
  contract_version: parsed.contract_version,
@@ -66884,6 +67267,8 @@ async function captureLearning(input, persistence, lessonDestination, skillDesti
66884
67267
  };
66885
67268
  }
66886
67269
  if (route === "private_skill") {
67270
+ markCaptureLearningStage("encrypted_persistence");
67271
+ markCaptureLearningPersisting();
66887
67272
  const link2 = parsed.replacement_of && "context_source" in parsed.replacement_of ? parsed.replacement_of : void 0;
66888
67273
  const draft = link2 ? await persistence.queuePrivateSkillReformulation(
66889
67274
  link2.draft_id,
@@ -66894,6 +67279,8 @@ async function captureLearning(input, persistence, lessonDestination, skillDesti
66894
67279
  parsed.private_skill,
66895
67280
  skillDestination
66896
67281
  );
67282
+ markCaptureLearningPersisted(draft.draft_id);
67283
+ markCaptureLearningStage("response");
66897
67284
  const recoveryContext = privateSkillRecoveryContext(draft);
66898
67285
  return {
66899
67286
  contract_version: parsed.contract_version,
@@ -66909,11 +67296,15 @@ async function captureLearning(input, persistence, lessonDestination, skillDesti
66909
67296
  persistence,
66910
67297
  lessonDestination,
66911
67298
  "capture_learning",
66912
- parsed.replacement_of?.draft_id
67299
+ parsed.replacement_of?.draft_id,
67300
+ parsed.replacement_of ? void 0 : currentCaptureLearningId()
66913
67301
  );
66914
67302
  return {
66915
67303
  contract_version: parsed.contract_version,
66916
67304
  capture_route: "private_lesson",
67305
+ ...!parsed.replacement_of ? { capture_id: currentCaptureLearningId() } : {},
67306
+ correlation_id: captureLearningCurrentDiagnostic()?.correlation_id,
67307
+ persistence_outcome: "persisted",
66917
67308
  ...prepared
66918
67309
  };
66919
67310
  }
@@ -66999,7 +67390,7 @@ function optionalPrivateSkillDraftId(value) {
66999
67390
  return value;
67000
67391
  }
67001
67392
  function unavailableInspection(lane, error) {
67002
- const diagnostic = privateOutboxDiagnostic(error);
67393
+ const diagnostic2 = privateOutboxDiagnostic(error);
67003
67394
  return {
67004
67395
  status: "unavailable",
67005
67396
  drafts: [],
@@ -67007,8 +67398,8 @@ function unavailableInspection(lane, error) {
67007
67398
  recovery_items: [],
67008
67399
  error_code: `${lane}_inspection_failed`,
67009
67400
  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 } : {}
67401
+ 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.",
67402
+ ...diagnostic2 ? { diagnostic: diagnostic2 } : {}
67012
67403
  };
67013
67404
  }
67014
67405
  function privateOutboxDiagnostic(error) {
@@ -67017,6 +67408,12 @@ function privateOutboxDiagnostic(error) {
67017
67408
  return { reason_code, stage, remediation };
67018
67409
  }
67019
67410
  async function inspectPrivateLessonOutbox(input, persistence, destination) {
67411
+ if (input.capture_id) {
67412
+ input = {
67413
+ ...input,
67414
+ draft_id: privateLessonCaptureDraftId(input.capture_id)
67415
+ };
67416
+ }
67020
67417
  const snapshot = await persistence.inspectPrivateLessonOutbox(
67021
67418
  input.limit,
67022
67419
  input.offset
@@ -67028,6 +67425,8 @@ async function inspectPrivateLessonOutbox(input, persistence, destination) {
67028
67425
  );
67029
67426
  if (completion) {
67030
67427
  return {
67428
+ ...input.capture_id ? { capture_id: input.capture_id } : {},
67429
+ persistence_outcome: "persisted",
67031
67430
  draft: privateLessonSubmittedActionResult(completion),
67032
67431
  outbox: publicOutboxSummary(snapshot.summary),
67033
67432
  recovery_items: snapshot.recovery_items
@@ -67035,12 +67434,20 @@ async function inspectPrivateLessonOutbox(input, persistence, destination) {
67035
67434
  }
67036
67435
  const draft = await persistence.readPrivateLessonDraft(input.draft_id);
67037
67436
  return {
67437
+ ...input.capture_id ? { capture_id: input.capture_id } : {},
67438
+ persistence_outcome: "persisted",
67038
67439
  draft: privateLessonDraftActionResult(draft, destination),
67039
67440
  outbox: publicOutboxSummary(snapshot.summary),
67040
67441
  recovery_items: snapshot.recovery_items
67041
67442
  };
67042
67443
  } catch (error) {
67043
67444
  return {
67445
+ ...input.capture_id ? { capture_id: input.capture_id } : {},
67446
+ persistence_outcome: "unknown",
67447
+ ...error instanceof PrivateLessonDraftUnavailableError && error.reason === "unknown" ? {
67448
+ local_record_outcome: "not_found",
67449
+ 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."
67450
+ } : {},
67044
67451
  selected_draft_error: privateLessonSelectedDraftError(
67045
67452
  input.draft_id,
67046
67453
  error
@@ -67067,7 +67474,7 @@ function privateLessonPageNextAction(nextOffset, limit) {
67067
67474
  };
67068
67475
  }
67069
67476
  function privateLessonSelectedDraftError(draftId, error) {
67070
- const diagnostic = error instanceof PrivateLessonDraftUnavailableError || error instanceof PrivateOutboxDecryptionError ? error.diagnostic() : error instanceof PrivateOutboxStorageError ? {
67477
+ const diagnostic2 = error instanceof PrivateLessonDraftUnavailableError || error instanceof PrivateOutboxDecryptionError ? error.diagnostic() : error instanceof PrivateOutboxStorageError ? {
67071
67478
  ...error.diagnostic(),
67072
67479
  code: error.reasonCode,
67073
67480
  draft_id: draftId,
@@ -67085,9 +67492,9 @@ function privateLessonSelectedDraftError(draftId, error) {
67085
67492
  };
67086
67493
  return {
67087
67494
  status: "unavailable",
67088
- error_code: diagnostic.code,
67089
- reason_code: diagnostic.code,
67090
- ...diagnostic
67495
+ error_code: diagnostic2.code,
67496
+ reason_code: diagnostic2.code,
67497
+ ...diagnostic2
67091
67498
  };
67092
67499
  }
67093
67500
  function privateLessonHealthReportingEnabled(env = process.env) {
@@ -67119,6 +67526,15 @@ function privateLessonDraftActionResult(draft, destination, extra = {}) {
67119
67526
  };
67120
67527
  }
67121
67528
  function privateLessonNextAction(draft) {
67529
+ if (ownerAttestedLegacyPrivateLessonRecoveryEligible(draft)) {
67530
+ return {
67531
+ tool: "retry_private_lesson_candidate",
67532
+ arguments: {
67533
+ draft_id: draft.draft_id,
67534
+ legacy_destination_recovery: { action: "review" }
67535
+ }
67536
+ };
67537
+ }
67122
67538
  if (draft.state === "ready") {
67123
67539
  return {
67124
67540
  tool: "submit_private_lesson_candidate",
@@ -67139,15 +67555,6 @@ function privateLessonNextAction(draft) {
67139
67555
  };
67140
67556
  }
67141
67557
  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
67558
  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
67559
  return {
67153
67560
  tool: "retry_private_lesson_candidate",
@@ -67181,15 +67588,15 @@ function privateLessonActionRequired(draft, destination) {
67181
67588
  !privateLessonReplaceable(draft, destination)
67182
67589
  );
67183
67590
  }
67591
+ if (ownerAttestedLegacyPrivateLessonRecoveryEligible(draft) && draft.last_error_code === "private_lesson_destination_legacy_unbound") {
67592
+ 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.";
67593
+ }
67184
67594
  if (draft.state === "awaiting_authorization") {
67185
67595
  return "Restore authorization for the exact private-lesson submission action, then retry this retained draft.";
67186
67596
  }
67187
67597
  if (draft.state === "retry_scheduled") {
67188
67598
  return "Retry the exact retained draft at or after next_retry_at.";
67189
67599
  }
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
67600
  if (draft.state === "held_validation" && draft.last_error_code === "private_lesson_destination_api_changed") {
67194
67601
  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
67602
  }
@@ -67308,12 +67715,12 @@ function privateSkillSelectedSubmittedResult(completion) {
67308
67715
  }
67309
67716
  function privateSkillSelectedDraftError(draftId, error) {
67310
67717
  if (error instanceof PrivateSkillDraftDeletedError) {
67311
- const diagnostic = error.diagnostic();
67718
+ const diagnostic2 = error.diagnostic();
67312
67719
  return {
67313
67720
  status: "unavailable",
67314
- error_code: diagnostic.code,
67315
- reason_code: diagnostic.code,
67316
- ...diagnostic
67721
+ error_code: diagnostic2.code,
67722
+ reason_code: diagnostic2.code,
67723
+ ...diagnostic2
67317
67724
  };
67318
67725
  }
67319
67726
  return {
@@ -67366,7 +67773,7 @@ function publicOutboxSummary(summary) {
67366
67773
  }
67367
67774
 
67368
67775
  // ../codex-plugin/scripts/feedback-disposition.mjs
67369
- import { createHash as createHash4, randomBytes as randomBytes6 } from "node:crypto";
67776
+ import { createHash as createHash4, randomBytes as randomBytes7 } from "node:crypto";
67370
67777
  import {
67371
67778
  chmodSync,
67372
67779
  closeSync as closeSync3,
@@ -67583,7 +67990,7 @@ function cleanupExpiredMarkers(directory, now) {
67583
67990
  }
67584
67991
  }
67585
67992
  function writeMarkerAtomically(path, marker) {
67586
- const temporaryPath = `${path}.${randomBytes6(8).toString("hex")}.tmp`;
67993
+ const temporaryPath = `${path}.${randomBytes7(8).toString("hex")}.tmp`;
67587
67994
  let descriptor;
67588
67995
  try {
67589
67996
  descriptor = openSync3(
@@ -67743,9 +68150,10 @@ function createLocalPersistenceCapabilities(dependencies = {}) {
67743
68150
  readKey: (source) => readExistingPrivateLessonOutboxKeyForSource(source, process.env, {})
67744
68151
  }),
67745
68152
  queuePrivateSkillHandoff: (payload, uploadBaseUrl) => queuePrivateSkillHandoff(payload, { uploadBaseUrl }),
67746
- queuePreparedPrivateLesson: async (prepared, destination) => queuePreparedPrivateLesson(prepared, null, {
68153
+ queuePreparedPrivateLesson: async (prepared, destination, captureId) => queuePreparedPrivateLesson(prepared, null, {
67747
68154
  ...await withEncryption(),
67748
- ...destination ? { destination } : {}
68155
+ ...destination ? { destination } : {},
68156
+ ...captureId ? { captureId } : {}
67749
68157
  }),
67750
68158
  queuePrivateLessonReplacement: async (replacementOf, prepared, destination) => queuePrivateLessonReplacement(replacementOf, prepared, {
67751
68159
  ...await withEncryption(),
@@ -67795,8 +68203,8 @@ function createLocalPersistenceCapabilities(dependencies = {}) {
67795
68203
  }
67796
68204
 
67797
68205
  // ../core/src/redaction-request-budget.ts
67798
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
67799
- var requests = new AsyncLocalStorage2();
68206
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
68207
+ var requests = new AsyncLocalStorage3();
67800
68208
  trackRedactionRequests(() => requests.getStore());
67801
68209
  function withRedactionRequestBudget(run) {
67802
68210
  return requests.getStore() ? run() : requests.run({}, run);
@@ -67854,8 +68262,8 @@ function inspectReviewRepairForTransport(value) {
67854
68262
  }
67855
68263
 
67856
68264
  // src/network-transport.ts
67857
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
67858
- var networkExecutionAuthority = new AsyncLocalStorage3();
68265
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
68266
+ var networkExecutionAuthority = new AsyncLocalStorage4();
67859
68267
  var guardedFetches = /* @__PURE__ */ new WeakSet();
67860
68268
  function installRuntimeFetchGuard() {
67861
68269
  const delegate = globalThis.fetch;
@@ -67905,7 +68313,7 @@ import {
67905
68313
  rmSync as rmSync2,
67906
68314
  writeFileSync as writeFileSync2
67907
68315
  } from "node:fs";
67908
- import { createHash as createHash5, randomBytes as randomBytes7 } from "node:crypto";
68316
+ import { createHash as createHash5, randomBytes as randomBytes8 } from "node:crypto";
67909
68317
  import { isIP } from "node:net";
67910
68318
  import { homedir as homedir9 } from "node:os";
67911
68319
  import { join as join10 } from "node:path";
@@ -68563,7 +68971,7 @@ function recordConnectionDoctorLifecycleProbe(options = {}) {
68563
68971
  );
68564
68972
  const path = join10(healthDir, `${rawSurface}.json`);
68565
68973
  if (!existsSync5(path)) return false;
68566
- const temporaryPath = `${path}.${process.pid}.${randomBytes7(6).toString("hex")}.tmp`;
68974
+ const temporaryPath = `${path}.${process.pid}.${randomBytes8(6).toString("hex")}.tmp`;
68567
68975
  try {
68568
68976
  const parsed = JSON.parse(
68569
68977
  readSecureLocalText(path, {
@@ -69569,6 +69977,173 @@ function isRecord10(value) {
69569
69977
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
69570
69978
  }
69571
69979
 
69980
+ // src/legacy-lesson-destination-recovery.ts
69981
+ var CONTRACT_VERSION = "private-lesson-legacy-destination-recovery-v1";
69982
+ var DIGEST3 = /^sha256:[a-f0-9]{64}$/u;
69983
+ async function legacyLessonDestinationRecovery(draft, destination, request, dependencies) {
69984
+ const alreadyRecovered = isRecoveredForDestination(draft, destination);
69985
+ if (!ownerAttestedLegacyPrivateLessonRecoveryEligible(draft) && !alreadyRecovered) {
69986
+ return refused(draft, "private_lesson_destination_recovery_ineligible");
69987
+ }
69988
+ if (request.action === "approve" && !validApproval(request)) {
69989
+ return refused(draft, "private_lesson_destination_recovery_approval_required");
69990
+ }
69991
+ if (request.action === "approve" && (request.expected_payload_digest !== draft.payload_digest || canonicalJson(request.expected_destination) !== canonicalJson(destination))) {
69992
+ return refused(draft, "private_lesson_destination_recovery_review_stale");
69993
+ }
69994
+ let audience;
69995
+ try {
69996
+ audience = await dependencies.verifiedOrganizationAudience();
69997
+ if (!DIGEST3.test(audience)) throw new Error("Invalid verified audience.");
69998
+ } catch {
69999
+ return refused(draft, "private_lesson_destination_recovery_policy_unavailable");
70000
+ }
70001
+ if (alreadyRecovered && draft.attested_organization_audience_hash !== audience || draft.policy !== null && draft.policy.organization_audience_hash !== audience) {
70002
+ return refused(draft, "private_lesson_destination_recovery_review_stale");
70003
+ }
70004
+ const plan = recoveryPlan(draft, destination, audience);
70005
+ if (request.action === "review") {
70006
+ if (alreadyRecovered) return recovered(draft, plan, "already_recovered");
70007
+ return {
70008
+ ...base(draft),
70009
+ status: "destination_recovery_review",
70010
+ persistence_outcome: "unchanged",
70011
+ plan,
70012
+ requires_explicit_owner_approval: true,
70013
+ 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.`,
70014
+ next_action: {
70015
+ tool: "retry_private_lesson_candidate",
70016
+ arguments: {
70017
+ draft_id: draft.draft_id,
70018
+ legacy_destination_recovery: {
70019
+ action: "approve",
70020
+ review_id: plan.review_id,
70021
+ expected_payload_digest: draft.payload_digest,
70022
+ expected_destination: destination,
70023
+ organization_audience_hash: audience
70024
+ }
70025
+ },
70026
+ requires_explicit_owner_approval: true,
70027
+ required_owner_input: [
70028
+ "owner_attested_single_organization",
70029
+ "all_outbox_readers_updated",
70030
+ "owner_attestation_sha256"
70031
+ ],
70032
+ 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."
70033
+ }
70034
+ };
70035
+ }
70036
+ if (request.review_id !== plan.review_id || request.organization_audience_hash !== audience) {
70037
+ return refused(draft, "private_lesson_destination_recovery_review_stale");
70038
+ }
70039
+ if (alreadyRecovered) {
70040
+ return recovered(draft, plan, "already_recovered");
70041
+ }
70042
+ try {
70043
+ const receipt = await dependencies.recover({
70044
+ draft_id: draft.draft_id,
70045
+ expected_payload_digest: draft.payload_digest,
70046
+ destination,
70047
+ organization_audience_hash: audience,
70048
+ owner_attested_single_organization: true,
70049
+ owner_attestation_sha256: request.owner_attestation_sha256
70050
+ });
70051
+ return {
70052
+ ...recovered(draft, plan, "destination_recovered"),
70053
+ recovery_receipt: receipt
70054
+ };
70055
+ } catch {
70056
+ try {
70057
+ const current = await dependencies.readDraft(draft.draft_id);
70058
+ if (current.payload_digest === draft.payload_digest && isRecoveredForDestination(current, destination) && current.attested_organization_audience_hash === audience) {
70059
+ return recovered(current, plan, "already_recovered");
70060
+ }
70061
+ if (ownerAttestedLegacyPrivateLessonRecoveryEligible(current) && current.payload_digest === draft.payload_digest) {
70062
+ return refused(current, "private_lesson_destination_recovery_not_applied");
70063
+ }
70064
+ } catch {
70065
+ }
70066
+ return {
70067
+ ...base(draft),
70068
+ status: "destination_recovery_unknown",
70069
+ error_code: "private_lesson_destination_recovery_outcome_unknown",
70070
+ failure_stage: "destination_recovery",
70071
+ persistence_outcome: "unknown",
70072
+ retained_locally: null,
70073
+ 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.",
70074
+ next_action: {
70075
+ tool: "retry_private_lesson_candidate",
70076
+ arguments: {
70077
+ draft_id: draft.draft_id,
70078
+ legacy_destination_recovery: request
70079
+ }
70080
+ }
70081
+ };
70082
+ }
70083
+ }
70084
+ function isRecoveredForDestination(draft, destination) {
70085
+ return draft.attested_organization_audience_hash !== void 0 && draft.destination_binding !== null && canonicalJson(draft.destination_binding) === canonicalJson(destination) && draft.last_error_code !== "private_lesson_destination_attestation_mismatch" && draft.state !== "submitted" && draft.state !== "superseded_redactor";
70086
+ }
70087
+ function validApproval(request) {
70088
+ return request.owner_attested_single_organization === true && request.all_outbox_readers_updated === true && DIGEST3.test(request.review_id) && DIGEST3.test(request.expected_payload_digest) && DIGEST3.test(request.owner_attestation_sha256) && DIGEST3.test(request.organization_audience_hash);
70089
+ }
70090
+ function recoveryPlan(draft, destination, audience) {
70091
+ const fields2 = {
70092
+ contract_version: CONTRACT_VERSION,
70093
+ draft_id: draft.draft_id,
70094
+ payload_digest: draft.payload_digest,
70095
+ destination,
70096
+ organization_audience_hash: audience,
70097
+ original_identity_sha256: hashValue(canonicalJson({
70098
+ draft_id: draft.draft_id,
70099
+ payload_digest: draft.payload_digest,
70100
+ redaction_version: draft.redaction_version,
70101
+ redactor_digest: draft.redactor_digest,
70102
+ idempotency_key: draft.idempotency_key,
70103
+ created_at: draft.created_at
70104
+ })),
70105
+ minimum_reader_version: "0.2.6"
70106
+ };
70107
+ return { ...fields2, review_id: hashValue(canonicalJson(fields2)) };
70108
+ }
70109
+ function base(draft) {
70110
+ return {
70111
+ contract_version: CONTRACT_VERSION,
70112
+ draft_id: draft.draft_id,
70113
+ payload_digest: draft.payload_digest,
70114
+ retained_locally: true,
70115
+ candidate_sent: false,
70116
+ retained_source_available_to_agent: false
70117
+ };
70118
+ }
70119
+ function recovered(draft, plan, status) {
70120
+ return {
70121
+ ...base(draft),
70122
+ status,
70123
+ persistence_outcome: "destination_bound",
70124
+ plan,
70125
+ 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.",
70126
+ next_action: {
70127
+ tool: "retry_private_lesson_candidate",
70128
+ arguments: { draft_id: draft.draft_id }
70129
+ }
70130
+ };
70131
+ }
70132
+ function refused(draft, code) {
70133
+ return {
70134
+ ...base(draft),
70135
+ status: "destination_recovery_refused",
70136
+ error_code: code,
70137
+ failure_stage: "destination_recovery_review",
70138
+ persistence_outcome: "unchanged",
70139
+ 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.",
70140
+ next_action: {
70141
+ tool: "inspect_private_lesson_outbox",
70142
+ arguments: { draft_id: draft.draft_id }
70143
+ }
70144
+ };
70145
+ }
70146
+
69572
70147
  // src/server.ts
69573
70148
  function inspectPrivateLearningOutbox2(input, dependencies = {}) {
69574
70149
  return inspectPrivateLearningOutbox(
@@ -69580,7 +70155,7 @@ function inspectPrivateLearningOutbox2(input, dependencies = {}) {
69580
70155
  }
69581
70156
  var MAX_REMOTE_RESPONSE_BYTES = 4 * 1024 * 1024;
69582
70157
  var DOCTOR_PROBE_TIMEOUT_MS = 7500;
69583
- var SERVER_VERSION = true ? "0.2.7" : "0.0.0-dev";
70158
+ var SERVER_VERSION = true ? "0.2.8" : "0.0.0-dev";
69584
70159
  var tools2 = toolDefinitions;
69585
70160
  var doctorCliRequested = process.argv[2] === "doctor";
69586
70161
  var nativeContextCliRequested = process.argv[2] === "--native-context";
@@ -69828,19 +70403,41 @@ async function dispatchJsonRpcRequest(request) {
69828
70403
  error: { code: -32602, message: `Unknown tool: ${name}` }
69829
70404
  };
69830
70405
  }
69831
- let result;
69832
70406
  try {
69833
- result = await callTool(definition, request.params?.arguments);
70407
+ const execute = async () => {
70408
+ const result2 = await callTool(definition, request.params?.arguments);
70409
+ markCaptureLearningStage("response");
70410
+ return remembranceMcpToolCallResult(result2, definition.name);
70411
+ };
70412
+ const result = name === "capture_learning" ? await withCaptureLearningDiagnostics(execute) : await execute();
70413
+ return { id: request.id, result };
69834
70414
  } catch (error) {
70415
+ const capture2 = captureLearningDiagnostic(error);
70416
+ if (capture2) {
70417
+ try {
70418
+ process.stderr.write(
70419
+ `${JSON.stringify({
70420
+ event: "capture_learning_failed",
70421
+ occurred_at: (/* @__PURE__ */ new Date()).toISOString(),
70422
+ server_version: SERVER_VERSION,
70423
+ code: capture2.code,
70424
+ correlation_id: capture2.correlation_id,
70425
+ capture_id: capture2.capture_id,
70426
+ failure_stage: capture2.failure_stage,
70427
+ persistence_outcome: capture2.persistence_outcome,
70428
+ ...capture2.draft_id ? { draft_id: capture2.draft_id } : {},
70429
+ ...capture2.reconciliation_draft_id ? { reconciliation_draft_id: capture2.reconciliation_draft_id } : {}
70430
+ })}
70431
+ `
70432
+ );
70433
+ } catch {
70434
+ }
70435
+ }
69835
70436
  return {
69836
70437
  id: request.id,
69837
70438
  error: jsonRpcErrorForToolError(error)
69838
70439
  };
69839
70440
  }
69840
- return {
69841
- id: request.id,
69842
- result: remembranceMcpToolCallResult(result, definition.name)
69843
- };
69844
70441
  }
69845
70442
  if (request.id !== void 0) {
69846
70443
  return {
@@ -69854,6 +70451,17 @@ async function dispatchJsonRpcRequest(request) {
69854
70451
  return null;
69855
70452
  }
69856
70453
  function jsonRpcErrorForToolError(error) {
70454
+ const classified = classifiedJsonRpcErrorForToolError(error);
70455
+ const capture2 = captureLearningDiagnostic(error);
70456
+ if (!capture2) return classified;
70457
+ 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.";
70458
+ return {
70459
+ ...classified,
70460
+ 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,
70461
+ data: { ...capture2, ...classified.data }
70462
+ };
70463
+ }
70464
+ function classifiedJsonRpcErrorForToolError(error) {
69857
70465
  if (error instanceof PrivateLessonDraftUnavailableError || error instanceof PrivateSkillRecoveryContextError || error instanceof PrivateSkillDraftUnavailableError) {
69858
70466
  return {
69859
70467
  code: error.jsonRpcCode(),
@@ -69892,14 +70500,17 @@ function jsonRpcErrorForToolError(error) {
69892
70500
  var McpPublicError = class extends Error {
69893
70501
  };
69894
70502
  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
- );
70503
+ const execute = () => {
70504
+ const runtimeDefinition = canonicalToolDefinitionForDispatch(definition);
70505
+ return runWithRemembranceNetworkExecution(
70506
+ {
70507
+ toolName: runtimeDefinition.name,
70508
+ networkBehavior: runtimeDefinition.executionNetworkBehavior
70509
+ },
70510
+ () => callToolWithinExecution(runtimeDefinition, rawArguments, dependencies)
70511
+ );
70512
+ };
70513
+ return definition.name === "capture_learning" ? withCaptureLearningDiagnostics(execute) : execute();
69903
70514
  }
69904
70515
  async function callToolWithinExecution(runtimeDefinition, rawArguments, dependencies) {
69905
70516
  if ((dependencies.testSchemaOverride || dependencies.testLocalOnlyExecutor) && process.env.NODE_ENV !== "test") {
@@ -69957,7 +70568,10 @@ async function callNetworkToolWithinExecution(definition, payload, access, trans
69957
70568
  access,
69958
70569
  "retry",
69959
70570
  transport,
69960
- { deliverRecheckedHold: args.deliver_rechecked_hold === true }
70571
+ {
70572
+ deliverRecheckedHold: args.deliver_rechecked_hold === true,
70573
+ legacyDestinationRecovery: args.legacy_destination_recovery
70574
+ }
69961
70575
  );
69962
70576
  }
69963
70577
  if (definition.local === "retry_private_skill_candidate") {
@@ -71058,7 +71672,7 @@ function privateLessonDestinationError(draft, current) {
71058
71672
  function privateLessonDestinationActionRequired(code) {
71059
71673
  switch (code) {
71060
71674
  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.";
71675
+ 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
71676
  case "private_lesson_destination_api_changed":
71063
71677
  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
71678
  case "private_lesson_destination_credential_changed":
@@ -71070,17 +71684,17 @@ function privateLessonDestinationActionRequired(code) {
71070
71684
  }
71071
71685
  }
71072
71686
  function privateLessonDestinationNextAction(draftId, code) {
71073
- if (code === "private_lesson_destination_legacy_unbound") {
71687
+ if (code === "private_lesson_destination_legacy_unbound" || code === "private_lesson_destination_attestation_mismatch") {
71074
71688
  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"]
71689
+ tool: "retry_private_lesson_candidate",
71690
+ arguments: {
71691
+ draft_id: draftId,
71692
+ legacy_destination_recovery: { action: "review" }
71693
+ }
71080
71694
  };
71081
71695
  }
71082
71696
  return {
71083
- tool: code === "private_lesson_destination_attestation_mismatch" ? "inspect_private_lesson_outbox" : "retry_private_lesson_candidate",
71697
+ tool: "retry_private_lesson_candidate",
71084
71698
  arguments: { draft_id: draftId }
71085
71699
  };
71086
71700
  }
@@ -71093,7 +71707,10 @@ async function holdPrivateLessonDestination(draft, code) {
71093
71707
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
71094
71708
  }));
71095
71709
  }
71096
- async function submitPrivateLessonDraft(draftId, access, mode, transport, { deliverRecheckedHold = false } = {}) {
71710
+ async function submitPrivateLessonDraft(draftId, access, mode, transport, {
71711
+ deliverRecheckedHold = false,
71712
+ legacyDestinationRecovery
71713
+ } = {}) {
71097
71714
  const allowPolicyRefresh = mode === "retry";
71098
71715
  const currentDestination = privateLessonDestinationForAccess(access);
71099
71716
  const source = await readPrivateLessonSubmissionSource(draftId);
@@ -71125,6 +71742,18 @@ async function submitPrivateLessonDraft(draftId, access, mode, transport, { deli
71125
71742
  status: "already_submitted"
71126
71743
  });
71127
71744
  }
71745
+ if (legacyDestinationRecovery) {
71746
+ return legacyLessonDestinationRecovery(
71747
+ draft,
71748
+ currentDestination,
71749
+ legacyDestinationRecovery,
71750
+ {
71751
+ verifiedOrganizationAudience: async () => (await fetchVerifiedPrivateLessonPolicy(access, transport)).policy.payload.organization_audience_hash,
71752
+ recover: recoverOwnerAttestedLegacyPrivateLessonDestination,
71753
+ readDraft: readPrivateLessonDraft
71754
+ }
71755
+ );
71756
+ }
71128
71757
  if (deliverRecheckedHold && draft.state === "held_safety" && draft.held_reasons.length > 0) {
71129
71758
  try {
71130
71759
  draft = await releaseRecheckedPrivateLessonHold(draft.draft_id);
@@ -73164,9 +73793,9 @@ function formatConnectionDoctorReport(report) {
73164
73793
  `Private lesson action: ${report.private_lesson_automation.action.visibility}`
73165
73794
  );
73166
73795
  if (report.private_lesson_automation.outbox.diagnostic) {
73167
- const diagnostic = report.private_lesson_automation.outbox.diagnostic;
73796
+ const diagnostic2 = report.private_lesson_automation.outbox.diagnostic;
73168
73797
  lines2.push(
73169
- `Private lesson storage: ${diagnostic.reason_code} (${diagnostic.stage}). ${diagnostic.remediation}`
73798
+ `Private lesson storage: ${diagnostic2.reason_code} (${diagnostic2.stage}). ${diagnostic2.remediation}`
73170
73799
  );
73171
73800
  }
73172
73801
  if (report.private_lesson_automation.outbox.deletion_guidance) {