@remembrance-ai/mcp-server 0.2.4 → 0.2.6

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
@@ -471,6 +471,32 @@ function agentHostBySurface(surface) {
471
471
  function isPluginHostSurface(value) {
472
472
  return PLUGIN_HOSTS.some((host) => host.surface === value);
473
473
  }
474
+ var CODEX_CLI_LOOKUP = `set +eu; unalias codex 2>/dev/null || :; unset -f codex 2>/dev/null || :
475
+ if [ -n "$CODEX_CLI" ]; then
476
+ [ -x "$CODEX_CLI" ] || { printf 'CODEX_CLI is set but is not an executable file: %s\\n' "$CODEX_CLI" >&2; exit 1; }
477
+ else
478
+ best=-1
479
+ for c in "$(command -v codex 2>/dev/null)" \\
480
+ /Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex \\
481
+ /Applications/ChatGPT.app/Contents/Resources/codex \\
482
+ /Applications/Codex.app/Contents/Resources/codex; do
483
+ case "$c" in /*) [ -x "$c" ] || continue ;; *) continue ;; esac
484
+ out=$("$c" --version </dev/null 2>/dev/null) || continue
485
+ v=$(printf '%s\\n' "$out" | awk 'match($0, /[0-9]+[.][0-9]+[.][0-9]+/) { split(substr($0, RSTART, RLENGTH), n, "."); v = n[1] * 1000000 + n[2] * 1000 + n[3]; exit } END { print v + 0 }')
486
+ [ "$v" -gt "$best" ] && best=$v && CODEX_CLI=$c
487
+ done
488
+ [ -n "$CODEX_CLI" ] || { printf '%s\\n' "Codex CLI not found. Install the Codex CLI, or install or update the ChatGPT desktop app on macOS, or set CODEX_CLI to a Codex CLI path, then try again." >&2; exit 1; }
489
+ fi
490
+ printf 'Using Codex CLI: %s\\n' "$CODEX_CLI" >&2`;
491
+ function codexCliCommand(...steps) {
492
+ return ["(", CODEX_CLI_LOOKUP, steps.join(" &&\n "), ")"].join("\n");
493
+ }
494
+ var CODEX_PLUGIN_SETUP_COMMAND = codexCliCommand(
495
+ '"$CODEX_CLI" plugin marketplace add dreamarkinc/remembrance-skills',
496
+ '"$CODEX_CLI" plugin marketplace upgrade remembrance',
497
+ '"$CODEX_CLI" plugin add remembrance@remembrance',
498
+ '"$CODEX_CLI"'
499
+ );
474
500
 
475
501
  // ../../node_modules/zod/v3/external.js
476
502
  var external_exports = {};
@@ -4580,14 +4606,10 @@ var clientHealthReportSchema = external_exports.object({
4580
4606
 
4581
4607
  // ../core/src/client-release.ts
4582
4608
  var CLIENT_RELEASE_SCHEMA_VERSION = "1";
4583
- var CODEX_UPDATE_COMMAND = [
4584
- 'CODEX_CLI="${CODEX_CLI:-$(command -v codex || true)}"',
4585
- '[ -x "$CODEX_CLI" ] || CODEX_CLI="/Applications/ChatGPT.app/Contents/Resources/codex"',
4586
- '[ -x "$CODEX_CLI" ] || CODEX_CLI="/Applications/Codex.app/Contents/Resources/codex"',
4587
- `[ -x "$CODEX_CLI" ] || { printf '%s\\n' "Codex CLI not found. Install the Codex CLI, or update the ChatGPT desktop app, then try again." >&2; exit 1; }`,
4609
+ var CODEX_UPDATE_COMMAND = codexCliCommand(
4588
4610
  '"$CODEX_CLI" plugin marketplace upgrade remembrance',
4589
4611
  '"$CODEX_CLI" plugin add remembrance@remembrance --json'
4590
- ].join("\n");
4612
+ );
4591
4613
  var CLIENT_UPDATE_GUIDANCE = {
4592
4614
  codex: {
4593
4615
  surface: "codex",
@@ -4798,8 +4820,8 @@ function parseSurfaceReleases(value) {
4798
4820
  );
4799
4821
  }
4800
4822
  function isCanonicalIsoTimestamp(value) {
4801
- const timestamp = Date.parse(value);
4802
- return Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value;
4823
+ const timestamp2 = Date.parse(value);
4824
+ return Number.isFinite(timestamp2) && new Date(timestamp2).toISOString() === value;
4803
4825
  }
4804
4826
 
4805
4827
  // ../core/src/client-health-alerts.ts
@@ -4898,7 +4920,7 @@ var HOST_POLICY_OPERATION_CLASSES = /* @__PURE__ */ new Set([
4898
4920
  "feedback",
4899
4921
  "other"
4900
4922
  ]);
4901
- var CODEX_HOOK_REVIEW_COMMAND = `CODEX_CLI="\${CODEX_CLI:-$(command -v codex || true)}"; [ -x "$CODEX_CLI" ] || CODEX_CLI="/Applications/ChatGPT.app/Contents/Resources/codex"; [ -x "$CODEX_CLI" ] || CODEX_CLI="/Applications/Codex.app/Contents/Resources/codex"; [ -x "$CODEX_CLI" ] || { printf '%s\\n' "Codex CLI not found. Install the Codex CLI, or install or update the ChatGPT desktop app on macOS, then try again." >&2; exit 1; }; "$CODEX_CLI"`;
4923
+ var CODEX_HOOK_REVIEW_COMMAND = codexCliCommand('"$CODEX_CLI"');
4902
4924
  var CODEX_HOOK_EVENTS = [
4903
4925
  "SessionStart",
4904
4926
  "UserPromptSubmit",
@@ -4916,7 +4938,7 @@ function codexHookReviewAction(followupTool, reviewEvents = []) {
4916
4938
  function codexHookEvents(value) {
4917
4939
  return Array.isArray(value) ? CODEX_HOOK_EVENTS.filter((event) => value.includes(event)) : [];
4918
4940
  }
4919
- var CODEX_HOOKS_PENDING_APPROVAL_NOTICE = "Remembrance hooks await Codex approval: run codex, choose Review hooks, press t.";
4941
+ var CODEX_HOOKS_PENDING_APPROVAL_NOTICE = "Remembrance hooks await Codex approval: run_connection_doctor gives the command.";
4920
4942
  var CODEX_HOOK_TRUST_UNREADABLE_NOTICE = "Could not read Codex hook trust state; check hooks with run_connection_doctor.";
4921
4943
  var CODEX_MANAGED_HOOKS_ONLY_NOTICE = "Remembrance plugin hooks are off: Codex policy runs only managed hooks. Tools work.";
4922
4944
  function codexHooksPendingApproval(value, followupTool) {
@@ -7610,8 +7632,7 @@ var PRIVATE_LESSON_TAG_RELATIONAL_PREFIXES = /* @__PURE__ */ new Set([
7610
7632
  "sub"
7611
7633
  ]);
7612
7634
  var privateLessonCanonicalTagSchema = privateLessonTagSyntaxSchema.superRefine((tag, ctx) => {
7613
- const inspected = inspectPrivateLessonTag(tag);
7614
- if (inspected.tag !== tag || inspected.held_reasons.length > 0) {
7635
+ if (inspectPrivateLessonTag(tag).tag !== tag) {
7615
7636
  ctx.addIssue({
7616
7637
  code: external_exports.ZodIssueCode.custom,
7617
7638
  message: "tag must be canonical and pass private-lesson safety checks"
@@ -7978,10 +7999,10 @@ var EXISTING_REDACTION_MARKER = new RegExp(
7978
7999
  var REPLACEMENTS = [
7979
8000
  { category: "unicode_control", pattern: ZERO_WIDTH_OR_BIDI, hold: true },
7980
8001
  { category: "stack_trace", pattern: STACK_TRACE, hold: true },
7981
- { category: "screenshot", pattern: SCREENSHOT, hold: true },
8002
+ { category: "screenshot", pattern: SCREENSHOT, hold: false },
7982
8003
  { category: "connection_string", pattern: CONNECTION_STRING, hold: false },
7983
8004
  { category: "private_url", pattern: PRIVATE_URL, hold: false },
7984
- { category: "public_url", pattern: PUBLIC_URL, hold: true },
8005
+ { category: "public_url", pattern: PUBLIC_URL, hold: false },
7985
8006
  { category: "jwt", pattern: JWT, hold: false },
7986
8007
  { category: "cookie", pattern: COOKIE, hold: false },
7987
8008
  { category: "credential", pattern: CREDENTIAL, hold: false },
@@ -7991,24 +8012,24 @@ var REPLACEMENTS = [
7991
8012
  {
7992
8013
  category: "encoded_or_high_entropy",
7993
8014
  pattern: SHORT_PADDED_BASE64,
7994
- hold: true
8015
+ hold: false
7995
8016
  },
7996
8017
  {
7997
8018
  category: "encoded_or_high_entropy",
7998
8019
  pattern: SHORT_MIXED_OPAQUE,
7999
- hold: true
8020
+ hold: false
8000
8021
  },
8001
8022
  {
8002
8023
  category: "credential",
8003
8024
  pattern: SHORT_CONTEXTUAL_CREDENTIAL,
8004
8025
  hold: false
8005
8026
  },
8006
- { category: "encoded_or_high_entropy", pattern: HIGH_ENTROPY, hold: true },
8027
+ { category: "encoded_or_high_entropy", pattern: HIGH_ENTROPY, hold: false },
8007
8028
  { category: "path", pattern: FILE_PATH, hold: false },
8008
8029
  { category: "hostname", pattern: INTERNAL_HOSTNAME, hold: false },
8009
8030
  { category: "hostname", pattern: HOSTNAME, hold: false },
8010
8031
  { category: "identifier", pattern: IDENTIFIER, hold: false },
8011
- { category: "code_block", pattern: CODE_BLOCK, hold: true }
8032
+ { category: "code_block", pattern: CODE_BLOCK, hold: false }
8012
8033
  ];
8013
8034
  function normalizePrivateLessonText(value) {
8014
8035
  return value.normalize("NFC").replace(/\r\n?/gu, "\n").replace(/[\t ]+/gu, " ").replace(/ *\n */gu, "\n").replace(/\n{3,}/gu, "\n\n").trim();
@@ -8043,6 +8064,141 @@ function redactPrivateLessonText(value) {
8043
8064
  held_reasons: [...held].sort()
8044
8065
  };
8045
8066
  }
8067
+ function redactPrivateLessonTextWithSpans(value) {
8068
+ const normalized2 = normalizePrivateLessonText(value);
8069
+ const existingMarkers = [];
8070
+ let text = "";
8071
+ let origin = [];
8072
+ let cursor = 0;
8073
+ const keep = (from, to) => {
8074
+ text += normalized2.slice(from, to);
8075
+ for (let index = from; index < to; index += 1) {
8076
+ origin.push([index, index + 1]);
8077
+ }
8078
+ };
8079
+ const markers = new RegExp(
8080
+ EXISTING_REDACTION_MARKER.source,
8081
+ EXISTING_REDACTION_MARKER.flags
8082
+ );
8083
+ for (const match of normalized2.matchAll(markers)) {
8084
+ keep(cursor, match.index);
8085
+ const placeholder = `\uFFF0${existingMarkers.push(match[0]) - 1}\uFFF1`;
8086
+ text += placeholder;
8087
+ for (let index = 0; index < placeholder.length; index += 1) {
8088
+ origin.push([match.index, match.index + match[0].length]);
8089
+ }
8090
+ cursor = match.index + match[0].length;
8091
+ }
8092
+ keep(cursor, normalized2.length);
8093
+ const counts = {};
8094
+ const held = /* @__PURE__ */ new Set();
8095
+ const spans = [];
8096
+ for (const rule of REPLACEMENTS) {
8097
+ const marker = `[redacted:${rule.category}]`;
8098
+ let next = "";
8099
+ const nextOrigin = [];
8100
+ let position = 0;
8101
+ let matches = 0;
8102
+ for (const match of text.matchAll(
8103
+ new RegExp(rule.pattern.source, rule.pattern.flags)
8104
+ )) {
8105
+ next += text.slice(position, match.index);
8106
+ nextOrigin.push(...origin.slice(position, match.index));
8107
+ const start = origin[match.index]?.[0] ?? normalized2.length;
8108
+ const end = Math.max(
8109
+ start,
8110
+ origin[match.index + match[0].length - 1]?.[1] ?? start
8111
+ );
8112
+ spans.push({ category: rule.category, hold: rule.hold, start, end });
8113
+ next += marker;
8114
+ for (let index = 0; index < marker.length; index += 1) {
8115
+ nextOrigin.push([start, end]);
8116
+ }
8117
+ position = match.index + match[0].length;
8118
+ matches += 1;
8119
+ }
8120
+ if (matches === 0) continue;
8121
+ next += text.slice(position);
8122
+ nextOrigin.push(...origin.slice(position));
8123
+ text = next;
8124
+ origin = nextOrigin;
8125
+ counts[rule.category] = (counts[rule.category] ?? 0) + matches;
8126
+ if (rule.hold) held.add(rule.category);
8127
+ }
8128
+ text = text.replace(/\uFFF0(\d+)\uFFF1/gu, (_, index) => {
8129
+ return existingMarkers[Number(index)] ?? "[redacted:identifier]";
8130
+ });
8131
+ return {
8132
+ text: normalizePrivateLessonText(text),
8133
+ counts: privateLessonRedactionCountsSchema.parse(counts),
8134
+ held_reasons: [...held].sort(),
8135
+ spans
8136
+ };
8137
+ }
8138
+ var PRIVATE_LESSON_MAX_FINDINGS = 16;
8139
+ function privateLessonFindings(input) {
8140
+ const parsed = privateLessonPreparationInputSchema.parse(input);
8141
+ const findings = [];
8142
+ const textFields = [
8143
+ ...parsed.generalized_lesson ? [["generalized_lesson", parsed.generalized_lesson, 0]] : [],
8144
+ ...(parsed.stable_conditions ?? []).map(
8145
+ (condition, index) => [`stable_conditions[${index}]`, condition, 1 + index]
8146
+ )
8147
+ ];
8148
+ for (const [field, value, rank] of textFields) {
8149
+ const byCategory = /* @__PURE__ */ new Map();
8150
+ for (const span of redactPrivateLessonTextWithSpans(value).spans) {
8151
+ byCategory.set(span.category, [
8152
+ ...byCategory.get(span.category) ?? [],
8153
+ span
8154
+ ]);
8155
+ }
8156
+ for (const [category, spans] of byCategory) {
8157
+ const first = spans.find((span) => span.hold) ?? spans[0];
8158
+ findings.push({
8159
+ field,
8160
+ category,
8161
+ rule: "text_pattern",
8162
+ occurrences: spans.length,
8163
+ approx_offset: first.start,
8164
+ length: first.end - first.start,
8165
+ holds: spans.some((span) => span.hold),
8166
+ rank
8167
+ });
8168
+ }
8169
+ }
8170
+ (parsed.tags ?? []).forEach((tag, index) => {
8171
+ if (inspectPrivateLessonTag(tag).tag !== null) return;
8172
+ const lowered = normalizePrivateLessonText(tag).toLowerCase();
8173
+ const aliased = PRIVATE_LESSON_SAFE_TAG_ALIASES[lowered] ?? lowered;
8174
+ const spans = redactPrivateLessonTextWithSpans(aliased).spans;
8175
+ const rule = spans.length > 0 ? "tag_pattern" : privateLessonTagSyntaxSchema.safeParse(aliased).success ? "tag_identity" : "tag_format";
8176
+ const categories = spans.length > 0 ? [...new Set(spans.map((span) => span.category))] : ["identifier"];
8177
+ for (const category of categories) {
8178
+ const matched = spans.filter((span) => span.category === category);
8179
+ findings.push({
8180
+ field: `tags[${index}]`,
8181
+ category,
8182
+ rule,
8183
+ occurrences: Math.max(1, matched.length),
8184
+ approx_offset: matched[0]?.start ?? 0,
8185
+ length: matched[0] ? matched[0].end - matched[0].start : aliased.length,
8186
+ holds: false,
8187
+ rank: 1e3 + index
8188
+ });
8189
+ }
8190
+ });
8191
+ findings.sort(
8192
+ (left, right) => Number(right.holds) - Number(left.holds) || left.rank - right.rank || left.approx_offset - right.approx_offset
8193
+ );
8194
+ return {
8195
+ findings: findings.slice(0, PRIVATE_LESSON_MAX_FINDINGS).map(({ rank: _rank, ...finding }) => finding),
8196
+ findings_omitted: Math.max(
8197
+ 0,
8198
+ findings.length - PRIVATE_LESSON_MAX_FINDINGS
8199
+ )
8200
+ };
8201
+ }
8046
8202
  function preparePrivateLessonCandidate(input, options = {}) {
8047
8203
  input = privateLessonPreparationInputSchema.parse(input);
8048
8204
  const redactedParts = [
@@ -8061,14 +8217,13 @@ function preparePrivateLessonCandidate(input, options = {}) {
8061
8217
  }
8062
8218
  const tagParts = (input.tags ?? []).map(inspectPrivateLessonTag);
8063
8219
  const counts = {};
8064
- const held = /* @__PURE__ */ new Set();
8065
8220
  for (const part of [...redactedParts, ...tagParts]) {
8066
8221
  for (const [category, count] of Object.entries(part.counts)) {
8067
8222
  const key = category;
8068
8223
  counts[key] = Math.min(999, (counts[key] ?? 0) + Number(count));
8069
8224
  }
8070
- for (const reason of part.held_reasons) held.add(reason);
8071
8225
  }
8226
+ const held = new Set(redactedParts.flatMap((part) => part.held_reasons));
8072
8227
  const lesson = redactedParts[0]?.text || null;
8073
8228
  const candidate = privateLessonCanonicalPayloadSchema.parse({
8074
8229
  contract_version: PRIVATE_LESSON_CONTRACT_VERSION,
@@ -8124,6 +8279,7 @@ function computePrivateLessonRedactorDigest() {
8124
8279
  correlation_ids: "domain-separated-sha256-v1",
8125
8280
  tag_syntax: PRIVATE_LESSON_TAG_PATTERN.source,
8126
8281
  tag_safety: "redaction-plus-identity-hints-v2",
8282
+ tag_failure: "drop-and-count-v1",
8127
8283
  tag_identity_hints: [...PRIVATE_LESSON_TAG_IDENTITY_HINTS].sort(),
8128
8284
  tag_identity_label_suffixes: [
8129
8285
  ...PRIVATE_LESSON_TAG_IDENTITY_LABEL_SUFFIXES
@@ -8147,10 +8303,6 @@ function inspectPrivateLessonTag(value) {
8147
8303
  const aliased = PRIVATE_LESSON_SAFE_TAG_ALIASES[normalized2] ?? normalized2;
8148
8304
  const redacted = redactPrivateLessonText(aliased);
8149
8305
  const counts = { ...redacted.counts };
8150
- const held = /* @__PURE__ */ new Set([
8151
- ...redacted.held_reasons,
8152
- ...Object.keys(redacted.counts)
8153
- ]);
8154
8306
  const identityHints = new Set(
8155
8307
  aliased.split(/[-_]/u).filter((segment) => PRIVATE_LESSON_TAG_IDENTITY_HINTS.has(segment))
8156
8308
  );
@@ -8158,21 +8310,10 @@ function inspectPrivateLessonTag(value) {
8158
8310
  const isGenericOrganizationRelationship = segments.length === 2 && PRIVATE_LESSON_TAG_RELATIONAL_PREFIXES.has(segments[0] ?? "") && PRIVATE_LESSON_TAG_IDENTITY_LABEL_SUFFIXES.has(segments[1] ?? "");
8159
8311
  const hasLikelyIdentityLabel = segments.length >= 2 && !isGenericOrganizationRelationship && PRIVATE_LESSON_TAG_IDENTITY_LABEL_SUFFIXES.has(segments.at(-1) ?? "") && segments.slice(0, -1).some((segment) => !PRIVATE_LESSON_TAG_IDENTITY_HINTS.has(segment));
8160
8312
  if (!privateLessonTagSyntaxSchema.safeParse(aliased).success || redacted.text !== aliased || identityHints.size >= 2 || hasLikelyIdentityLabel) {
8161
- if (held.size === 0) {
8162
- counts.identifier = Math.min(999, (counts.identifier ?? 0) + 1);
8163
- held.add("identifier");
8164
- }
8165
- return {
8166
- tag: null,
8167
- counts,
8168
- held_reasons: [...held].sort()
8169
- };
8313
+ if (Object.keys(counts).length === 0) counts.identifier = 1;
8314
+ return { tag: null, counts };
8170
8315
  }
8171
- return {
8172
- tag: aliased,
8173
- counts: {},
8174
- held_reasons: []
8175
- };
8316
+ return { tag: aliased, counts: {} };
8176
8317
  }
8177
8318
  function pseudonymizeCorrelationId(value) {
8178
8319
  const digest2 = hashValue(
@@ -8184,6 +8325,7 @@ function pseudonymizeCorrelationId(value) {
8184
8325
  return `corr_${digest2.slice(0, 48)}`;
8185
8326
  }
8186
8327
  var CURRENT_PRIVATE_LESSON_REDACTOR_DIGEST = computePrivateLessonRedactorDigest();
8328
+ var PRIVATE_LESSON_BROAD_HOLD_REDACTOR_DIGEST = "sha256:e3414b36b1f8d5512e42148c0d06b958c7010bbdb52024bd78ad4e68b0356324";
8187
8329
  var PRIVATE_LESSON_LEGACY_V2_REDACTOR_DIGEST = "sha256:bca83ac50b0124a0401f806b3498bbb1ec977c02c1975d5345cb8d0b85c00b75";
8188
8330
  var PRIVATE_LESSON_SUPPORTED_REDACTOR_PROFILES = Object.freeze({
8189
8331
  [PRIVATE_LESSON_REDACTION_VERSION]: Object.freeze({
@@ -8192,6 +8334,14 @@ var PRIVATE_LESSON_SUPPORTED_REDACTOR_PROFILES = Object.freeze({
8192
8334
  digest: CURRENT_PRIVATE_LESSON_REDACTOR_DIGEST,
8193
8335
  normalization: "unicode-nfc-lf-space-v1"
8194
8336
  }),
8337
+ // Retained drafts and candidates of published 0.2 clients keep a
8338
+ // supported profile; a candidate is still checked against the current
8339
+ // canonical schema and network-safety refinements.
8340
+ [PRIVATE_LESSON_BROAD_HOLD_REDACTOR_DIGEST]: Object.freeze({
8341
+ version: PRIVATE_LESSON_REDACTION_VERSION,
8342
+ digest: PRIVATE_LESSON_BROAD_HOLD_REDACTOR_DIGEST,
8343
+ normalization: "unicode-nfc-lf-space-v1"
8344
+ }),
8195
8345
  // Published pre-negotiation clients produced this exact v2 profile.
8196
8346
  // Retain it for the 0.2.x compatibility window; all candidates still pass
8197
8347
  // the current canonical schema and network-safety refinements.
@@ -8219,6 +8369,27 @@ var PrivateLessonRedactionProfileError = class extends Error {
8219
8369
  function privateLessonRedactorDigest() {
8220
8370
  return CURRENT_PRIVATE_LESSON_REDACTOR_DIGEST;
8221
8371
  }
8372
+ function privateLessonCurrentHoldReasons(candidate, heldReasons) {
8373
+ const known = new Set(privateLessonRedactionCategorySchema.options);
8374
+ const holding = new Set(
8375
+ REPLACEMENTS.filter((rule) => rule.hold).map((rule) => rule.category)
8376
+ );
8377
+ const text = [
8378
+ candidate.generalized_lesson ?? "",
8379
+ ...candidate.stable_conditions
8380
+ ].join("\n");
8381
+ return [
8382
+ .../* @__PURE__ */ new Set([
8383
+ ...[...holding].filter(
8384
+ (category) => text.includes(`[redacted:${category}]`)
8385
+ ),
8386
+ ...heldReasons.filter((category) => holding.has(category)),
8387
+ ...[...Object.keys(candidate.redaction_counts), ...heldReasons].filter(
8388
+ (category) => !known.has(category)
8389
+ )
8390
+ ])
8391
+ ].sort();
8392
+ }
8222
8393
  function privateLessonSupportedRedactorProfiles() {
8223
8394
  return Object.entries(PRIVATE_LESSON_SUPPORTED_REDACTOR_PROFILES).flatMap(
8224
8395
  ([redactionVersion, profiles]) => Object.keys(profiles).map((redactorDigest) => ({
@@ -8479,6 +8650,9 @@ var privateSkillReplacementLinkSchema = external_exports.object({
8479
8650
  context_source: privateSkillReformulationContextSourceSchema,
8480
8651
  recovery_context_id: external_exports.string().regex(/^pctx_[a-f0-9]{64}$/u).optional()
8481
8652
  }).strict();
8653
+ var privateLessonReplacementLinkSchema = external_exports.object({
8654
+ draft_id: external_exports.string().regex(/^pld_[A-Za-z0-9_-]{8,96}$/u)
8655
+ }).strict();
8482
8656
  var privateSkillCaptureSchema = privateSkillIdeaRequestSchema.omit({
8483
8657
  agent: true,
8484
8658
  enterprise_encryption: true,
@@ -8560,7 +8734,10 @@ var captureLearningInputSchema = external_exports.object({
8560
8734
  contract_version: external_exports.literal(PRIVATE_LEARNING_CAPTURE_VERSION).default(PRIVATE_LEARNING_CAPTURE_VERSION),
8561
8735
  lesson: privateLessonPreparationInputSchema.optional(),
8562
8736
  private_skill: privateSkillCaptureSchema.optional(),
8563
- replacement_of: privateSkillReplacementLinkSchema.optional(),
8737
+ replacement_of: external_exports.union([
8738
+ privateSkillReplacementLinkSchema,
8739
+ privateLessonReplacementLinkSchema
8740
+ ]).optional(),
8564
8741
  preference: recordPreferenceRequestSchema.optional()
8565
8742
  }).strict().superRefine((value, ctx) => {
8566
8743
  const populated = [
@@ -8574,10 +8751,11 @@ var captureLearningInputSchema = external_exports.object({
8574
8751
  message: "Exactly one lesson, private_skill, or preference payload is required."
8575
8752
  });
8576
8753
  }
8577
- if (value.replacement_of !== void 0 && value.private_skill === void 0) {
8754
+ const replaces = value.replacement_of?.draft_id.slice(0, 4);
8755
+ if (replaces === "psd_" && value.private_skill === void 0 || replaces === "pld_" && value.lesson === void 0) {
8578
8756
  ctx.addIssue({
8579
8757
  code: external_exports.ZodIssueCode.custom,
8580
- message: "replacement_of is valid only with a private_skill payload.",
8758
+ message: replaces === "psd_" ? "replacement_of with a private-skill draft_id is valid only with a private_skill payload." : "replacement_of with a private-lesson draft_id is valid only with a lesson payload.",
8581
8759
  path: ["replacement_of"]
8582
8760
  });
8583
8761
  }
@@ -8601,7 +8779,7 @@ function captureLearningRoute(input) {
8601
8779
 
8602
8780
  // ../core/src/agent-guidance.ts
8603
8781
  var REMEMBRANCE_QUERY_TOOL_DESCRIPTION = "Call before non-trivial service, API, tool, library, workflow, UI, review, test, security, or deployment work to find relevant Remembrance skills and resources. This is a read-only routine action: do not ask the user for a separate conversational permission step. For short context-dependent follow-ups, infer the concrete task from the full conversation, preserve any plugin-supplied client_context.directive_id/runtime/trigger_reason, and query anyway. Compare each candidate's bounded why_matched evidence and applicability conditions before opening it; discard stated unlikely or corner-case mismatches. High matches should be fetched before custom work; possible and exploratory matches remain optional. Do not use for broad web search or one-off facts. Results refer by key or preference_fingerprint to preferences stated once in top-level effective_preferences, and get_skill returns the full text of a description_truncated summary. semantic_status says, without content, whether vector retrieval contributed to each result list; lexical_only results remain usable.";
8604
- var REMEMBRANCE_QUERY_FEEDBACK_TOOL_DESCRIPTION = "Submit one complete set of bounded explicit good, partial, or poor judgments for result_id values from one query_skills call, using the same auth scope as that query. Use overall_fit none only when every rated result is poor; if any result is partial or good, use partial or good as appropriate. Keep honest per-result judgments when correcting validation errors; do not drop them or relabel matches to bypass validation. Each result_id appears once; poor ratings require at least one reason. This bounded feedback action carries no reusable content and needs no separate conversational permission request. Unrated results stay neutral. Notes are optional and compact; this path remains independent of private learning capture and never accepts a reusable lesson. An identical retry is safe, but changed later judgments conflict. Labels adjust bounded retrieval profiles without changing global skill usefulness; use submit_feedback only after actually using a skill.";
8782
+ var REMEMBRANCE_QUERY_FEEDBACK_TOOL_DESCRIPTION = "Submit one complete set of bounded explicit good, partial, or poor judgments for result_id values from one query_skills call, using the same auth scope as that query. Use overall_fit none only when every rated result is poor; if any result is partial or good, use partial or good as appropriate. Keep honest per-result judgments when correcting validation errors; do not drop them or relabel matches to bypass validation. Each result_id appears once; poor ratings require at least one reason. This bounded feedback action carries no reusable content and needs no separate conversational permission request. Unrated results stay neutral. Notes are optional and compact; this path remains independent of private learning capture and never accepts a reusable lesson. Keep routine organization ratings minimal: use the Remembrance-issued query_id and result_id values, judgments, required reasons, and an idempotency key when needed, and do not automatically attach internal artifact hashes, task text, source snippets, or raw logs. An identical retry is safe, but changed later judgments conflict. Labels adjust bounded retrieval profiles without changing global skill usefulness; use submit_feedback only after actually using a skill.";
8605
8783
  var REMEMBRANCE_INVOKE_SKILL_TOOL_DESCRIPTION = "Load an explicitly selected skill through the authoritative policy boundary. Use an exact slug returned by list_skills, an MCP resource, or query_skills. This resolves the current active reviewed version, records direct selection, and returns post-use feedback and outcome instructions. Pass version_id only when a session-start directive or subagent handoff supplies one; that exact version is loaded and never substituted, and 409 skill_version_unavailable means it cannot be served. Use scope session only for an organization session skill named by a session-start directive; omit scope for ordinary task use. Do not use submit_query_feedback for this explicit selection.";
8606
8784
  var REMEMBRANCE_CONNECTION_STATUS_TOOL_DESCRIPTION = "Inspect the active Remembrance transport, credential source, authenticated registry scope, and content-free recent contribution outcomes for the current installation or API key without exposing credentials or lesson content. Call this before diagnosing authentication, checking environment variables, or making anonymous REST/browser probes. Local or bundled MCP can read REMEMBRANCE_API_KEY or ~/.config/remembrance/config.json; hosted MCP cannot read local files and authenticates from its request header. When a declared native lifecycle is degraded, local MCP may submit bounded, content-free health evidence unless REMEMBRANCE_HEALTH_REPORTING=0. Never infer the plugin's scope from REMEMBRANCE_API_KEY alone.";
8607
8785
  var REMEMBRANCE_CONNECTION_DOCTOR_TOOL_DESCRIPTION = "Run a bounded, non-mutating Remembrance connection diagnostic. It verifies the active transport, a redacted registry destination, authenticated scope, query authorization, a real catalog read, and organization submission capability. Local MCP also checks shared-config permissions, destination consistency, native plugin lifecycle, and signing identity; hosted MCP marks local-only checks unavailable. It never submits content, creates query demand, opens a review item, or returns credentials, absolute paths, private registry URLs, prompts, or repository data.";
@@ -9900,6 +10078,9 @@ var MAX_RSA_FACTOR_SEARCH_MODULUS = 1n << 4096n;
9900
10078
  var MAX_RSA_ARITHMETIC_WORK = 2 ** 32;
9901
10079
  var MAX_REQUEST_RSA_ARITHMETIC_WORK = 2 ** 34;
9902
10080
  var currentRedactionRequest = () => void 0;
10081
+ function trackRedactionRequests(current) {
10082
+ currentRedactionRequest = current;
10083
+ }
9903
10084
  var MIN_DETACHED_RSA_CONTINUATION_BYTES = 16;
9904
10085
  var MAX_DETACHED_RSA_CONTINUATION_READS = 1 << 20;
9905
10086
  var detachedRsaContinuationReads = /* @__PURE__ */ new WeakMap();
@@ -10506,9 +10687,137 @@ function serializedPublicRsaKeyValueIsValid2(value, metrics) {
10506
10687
  function rsaPublicNumbersArePlausible2(modulus, exponent, metrics) {
10507
10688
  return rsaPublicNumbersArePlausible(modulus, exponent, metrics);
10508
10689
  }
10690
+ function redactPayload(payload) {
10691
+ const analysis = analyzeSensitivePayload(payload);
10692
+ return redactAnalyzedPayload(payload, analysis);
10693
+ }
10694
+ function redactAnalyzedPayload(payload, analysis) {
10695
+ if (!payload || typeof payload !== "object") {
10696
+ if (typeof payload !== "string") return payload;
10697
+ const baseline = redactStringValue(payload, analysis.metrics);
10698
+ const ranges = lateStringOverlapRanges(payload, analysis.metrics);
10699
+ analysis.sensitiveMaterial ||= ranges.length > 0;
10700
+ return applyLateOverlapRanges(baseline, ranges, analysis.metrics);
10701
+ }
10702
+ const valuePlans = /* @__PURE__ */ new Map();
10703
+ const keyPlans = /* @__PURE__ */ new Map();
10704
+ const outputKeys = /* @__PURE__ */ new Map();
10705
+ const clones = analysis.graph.containers.map(
10706
+ (container) => analysis.numericPrivateContainers.has(container) ? "[redacted]" : container.kind === "array" ? new Array(container.value.length) : {}
10707
+ );
10708
+ for (const container of analysis.graph.containers) {
10709
+ if (analysis.numericPrivateContainers.has(container)) continue;
10710
+ const target = clones[container.id];
10711
+ if (container.kind === "array") {
10712
+ for (const edge of container.edges) {
10713
+ target[edge.index] = redactedEdgeValue(
10714
+ edge,
10715
+ analysis,
10716
+ clones,
10717
+ valuePlans
10718
+ );
10719
+ }
10720
+ continue;
10721
+ }
10722
+ const objectTarget = target;
10723
+ const redactedKeys = analysis.sensitiveObjectKeys.get(container.value);
10724
+ const reservedKeys = new Set(
10725
+ container.edges.filter((edge) => !redactedKeys?.has(edge.key)).map((edge) => edge.key)
10726
+ );
10727
+ const usedKeys = /* @__PURE__ */ new Set();
10728
+ const nextSuffix = /* @__PURE__ */ new Map();
10729
+ for (const edge of container.edges) {
10730
+ const keyPlan = redactedKeys?.has(edge.key) ? redactStringValue(edge.key, analysis.metrics) : unchangedStringProjection(edge.key);
10731
+ const forcedKey = redactedKeys?.has(edge.key) && !keyPlan.changed;
10732
+ keyPlans.set(edge, forcedKey ? fullyRedactedStringProjection() : keyPlan);
10733
+ const outputKey = redactedKeys?.has(edge.key) ? uniqueRedactedObjectKey(
10734
+ reservedKeys,
10735
+ usedKeys,
10736
+ nextSuffix,
10737
+ forcedKey ? "[redacted]" : keyPlan.value
10738
+ ) : edge.key;
10739
+ outputKeys.set(edge, outputKey);
10740
+ usedKeys.add(outputKey);
10741
+ const value = isSensitiveKey(edge.key) && edge.value !== null && edge.value !== void 0 ? "[redacted]" : redactedEdgeValue(edge, analysis, clones, valuePlans);
10742
+ Object.defineProperty(objectTarget, outputKey, {
10743
+ value,
10744
+ enumerable: true,
10745
+ configurable: true,
10746
+ writable: true
10747
+ });
10748
+ }
10749
+ }
10750
+ const claims = latePayloadOverlapRanges(analysis, valuePlans, keyPlans);
10751
+ for (const container of analysis.graph.containers) {
10752
+ if (analysis.numericPrivateContainers.has(container)) continue;
10753
+ const target = clones[container.id];
10754
+ const renamed = /* @__PURE__ */ new Map();
10755
+ for (const edge of container.edges) {
10756
+ const valuePlan = valuePlans.get(edge);
10757
+ const valueRanges = edge.valueToken && claims.get(edge.valueToken);
10758
+ if (valuePlan && valueRanges) {
10759
+ const key = container.kind === "array" ? edge.index : outputKeys.get(edge);
10760
+ target[key] = applyLateOverlapRanges(
10761
+ valuePlan,
10762
+ valueRanges,
10763
+ analysis.metrics
10764
+ );
10765
+ }
10766
+ const keyPlan = keyPlans.get(edge);
10767
+ const keyRanges = edge.keyToken && claims.get(edge.keyToken);
10768
+ if (keyPlan && keyRanges) {
10769
+ const oldKey = outputKeys.get(edge);
10770
+ const candidate = applyLateOverlapRanges(
10771
+ { ...keyPlan, value: oldKey },
10772
+ keyRanges,
10773
+ analysis.metrics
10774
+ );
10775
+ if (candidate !== oldKey) renamed.set(edge, candidate);
10776
+ }
10777
+ }
10778
+ if (renamed.size === 0) continue;
10779
+ const reserved = new Set(
10780
+ container.edges.filter((edge) => !renamed.has(edge)).map((edge) => outputKeys.get(edge))
10781
+ );
10782
+ const used = /* @__PURE__ */ new Set();
10783
+ const suffixes = /* @__PURE__ */ new Map();
10784
+ const entries = container.edges.map((edge) => {
10785
+ const oldKey = outputKeys.get(edge);
10786
+ const candidate = renamed.get(edge);
10787
+ const key = candidate === void 0 ? oldKey : uniqueRedactedObjectKey(reserved, used, suffixes, candidate);
10788
+ used.add(key);
10789
+ return { oldKey, key, value: target[oldKey] };
10790
+ });
10791
+ for (const { oldKey } of entries) delete target[oldKey];
10792
+ for (const { key, value } of entries)
10793
+ Object.defineProperty(target, key, {
10794
+ value,
10795
+ enumerable: true,
10796
+ configurable: true,
10797
+ writable: true
10798
+ });
10799
+ }
10800
+ return clones[analysis.graph.root.id];
10801
+ }
10509
10802
  function containsSensitiveMaterial(payload) {
10510
10803
  return inspectPayloadForSensitiveMaterial(payload).sensitiveMaterial;
10511
10804
  }
10805
+ function redactedEdgeValue(edge, analysis, clones, plans) {
10806
+ if (edge.child) return clones[edge.child.id];
10807
+ if (typeof edge.value !== "string") return edge.value;
10808
+ const ranges = analysis.privateKeyBodyRanges.get(edge.owner.value)?.get(edge.key);
10809
+ const native = ranges ? projectedTextRanges(edge.value, ranges, analysis.metrics) : unchangedStringProjection(edge.value);
10810
+ const lexical = redactStringValue(native.value, analysis.metrics);
10811
+ plans.set(edge, {
10812
+ ...lexical,
10813
+ retained: composeRetainedSourceSpans(
10814
+ native.retained,
10815
+ lexical.retained,
10816
+ analysis.metrics
10817
+ )
10818
+ });
10819
+ return lexical.value;
10820
+ }
10512
10821
  function inspectPayloadForSensitiveMaterial(payload) {
10513
10822
  const analysis = analyzeSensitivePayload(payload);
10514
10823
  latePayloadOverlapRanges(analysis);
@@ -20513,6 +20822,16 @@ function isShortPemBoundaryFragment(value) {
20513
20822
  if (isCompletePemBoundary(trimmed)) return true;
20514
20823
  return trimmed.length <= 32 && /^-{5}(?:BEGIN|END)[A-Z0-9_-]{0,18}$/iu.test(trimmed) && exactPrivateKeyMarker2(trimmed) === null;
20515
20824
  }
20825
+ 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}`)) {
20830
+ suffix += 1;
20831
+ }
20832
+ nextSuffixByBase.set(base, suffix + 1);
20833
+ return `${base}-${suffix}`;
20834
+ }
20516
20835
  function createRedactionWorkMetrics() {
20517
20836
  return {
20518
20837
  nodesVisited: 0,
@@ -22612,6 +22931,9 @@ function unchangedStringProjection(value) {
22612
22931
  retained: value.length ? [{ start: 0, end: value.length, outputStart: 0 }] : []
22613
22932
  };
22614
22933
  }
22934
+ function fullyRedactedStringProjection() {
22935
+ return { value: "[redacted]", changed: true, retained: [] };
22936
+ }
22615
22937
  function appendRetainedSourceSpan(spans, span) {
22616
22938
  spans.push(span);
22617
22939
  }
@@ -22651,6 +22973,67 @@ function retainedAfterRedactionRanges(retained, ranges, metrics, replacementLeng
22651
22973
  }
22652
22974
  return result;
22653
22975
  }
22976
+ function projectedTextRanges(value, ranges, metrics) {
22977
+ if (ranges.length === 1 && ranges[0].start === 0 && ranges[0].end === value.length) {
22978
+ return fullyRedactedStringProjection();
22979
+ }
22980
+ const original = unchangedStringProjection(value);
22981
+ return {
22982
+ value: redactTextRanges(value, ranges),
22983
+ changed: ranges.length > 0,
22984
+ retained: retainedAfterRedactionRanges(original.retained, ranges, metrics)
22985
+ };
22986
+ }
22987
+ function composeRetainedSourceSpans(first, second, metrics) {
22988
+ if (first.length === 0 || second.length === 0) return [];
22989
+ const result = [];
22990
+ let leftIndex = 0;
22991
+ let rightIndex = 0;
22992
+ while (leftIndex < first.length && rightIndex < second.length) {
22993
+ metrics.ownershipSteps += 1;
22994
+ const left = first[leftIndex];
22995
+ const right = second[rightIndex];
22996
+ const leftEnd = left.outputStart + left.end - left.start;
22997
+ const start = Math.max(left.outputStart, right.start);
22998
+ const end = Math.min(leftEnd, right.end);
22999
+ if (start < end)
23000
+ appendRetainedSourceSpan(result, {
23001
+ start: left.start + start - left.outputStart,
23002
+ end: left.start + end - left.outputStart,
23003
+ outputStart: right.outputStart + start - right.start
23004
+ });
23005
+ if (leftEnd <= right.end) leftIndex += 1;
23006
+ if (right.end <= leftEnd) rightIndex += 1;
23007
+ }
23008
+ return result;
23009
+ }
23010
+ function applyLateOverlapRanges(baseline, claims, metrics) {
23011
+ if (claims.length === 0 || baseline.retained.length === 0)
23012
+ return baseline.value;
23013
+ const projected = [];
23014
+ let claimIndex = 0;
23015
+ for (const [index, span] of baseline.retained.entries()) {
23016
+ metrics.ownershipSteps += 1;
23017
+ while (claimIndex < claims.length && claims[claimIndex].end <= span.start) {
23018
+ metrics.ownershipSteps += 1;
23019
+ claimIndex += 1;
23020
+ }
23021
+ let current = claimIndex;
23022
+ while (current < claims.length && claims[current].start < span.end) {
23023
+ metrics.ownershipSteps += 1;
23024
+ const claim = claims[current++];
23025
+ const start = Math.max(span.start, claim.start);
23026
+ const end = Math.min(span.end, claim.end);
23027
+ const previous = baseline.retained[index - 1];
23028
+ const next = baseline.retained[index + 1];
23029
+ projected.push({
23030
+ start: start === span.start ? previous ? previous.outputStart + previous.end - previous.start : 0 : span.outputStart + start - span.start,
23031
+ end: end === span.end ? next ? next.outputStart : baseline.value.length : span.outputStart + end - span.start
23032
+ });
23033
+ }
23034
+ }
23035
+ return projected.length === 0 ? baseline.value : redactTextRanges(baseline.value, mergeOrderedTextRanges([], projected));
23036
+ }
22654
23037
  function latePayloadOverlapRanges(analysis, valuePlans, keyPlans) {
22655
23038
  const { graph, metrics } = analysis;
22656
23039
  const claims = /* @__PURE__ */ new Map();
@@ -23446,7 +23829,8 @@ var remembrance_mcp_consent_lanes_default = {
23446
23829
  propose_skill_idea: "skill_candidate",
23447
23830
  submit_suggestion: "skill_suggestion",
23448
23831
  submit_resource: "resource_submission",
23449
- submit_resource_review: "resource_review"
23832
+ submit_resource_review: "resource_review",
23833
+ repair_review_draft: "admin_review_repair"
23450
23834
  };
23451
23835
 
23452
23836
  // ../core/src/remembrance-mcp-policy.ts
@@ -23487,6 +23871,10 @@ var REMEMBRANCE_MCP_OPTIONAL_SHARED_CONTRIBUTION_TOOLS = Object.freeze(
23487
23871
  "register_agent_key"
23488
23872
  ]
23489
23873
  );
23874
+ var REMEMBRANCE_MCP_OPTIONAL_ADMIN_REVIEW_TOOLS = Object.freeze([
23875
+ "get_review_comparison",
23876
+ "repair_review_draft"
23877
+ ]);
23490
23878
  var REMEMBRANCE_MCP_LOCAL_ONLY_TOOLS = Object.freeze([
23491
23879
  "bootstrap_agent_identity",
23492
23880
  "acknowledge_feedback_denial",
@@ -23526,6 +23914,7 @@ var REMEMBRANCE_MCP_RECOMMENDED_LOCAL_ORG_TOOLS = Object.freeze([
23526
23914
  var REMEMBRANCE_MCP_ALL_TOOLS = Object.freeze([
23527
23915
  ...REMEMBRANCE_MCP_RECOMMENDED_ORG_TOOLS,
23528
23916
  ...REMEMBRANCE_MCP_OPTIONAL_SHARED_CONTRIBUTION_TOOLS,
23917
+ ...REMEMBRANCE_MCP_OPTIONAL_ADMIN_REVIEW_TOOLS,
23529
23918
  ...REMEMBRANCE_MCP_LOCAL_ONLY_TOOLS
23530
23919
  ]);
23531
23920
  var REMEMBRANCE_MCP_BOUNDED_WRITE_POLICY_MAX_BYTES_BY_PAYLOAD_CLASS = Object.freeze({
@@ -23621,6 +24010,8 @@ var REMEMBRANCE_MCP_TOOL_SECURITY = freezeMcpToolSecurityManifest({
23621
24010
  link_current_installation: bounded("bounded_metadata"),
23622
24011
  get_skill: read(),
23623
24012
  get_resource: read(),
24013
+ get_review_comparison: read(),
24014
+ repair_review_draft: content("repair_review_draft", "private_skill"),
23624
24015
  bootstrap_agent_identity: bounded("bounded_metadata"),
23625
24016
  acknowledge_feedback_denial: local("bounded_feedback"),
23626
24017
  decline_pending_action: local("bounded_metadata"),
@@ -23749,14 +24140,35 @@ var GEMINI_ADMIN_ALLOWED_TOOLS = Object.freeze(
23749
24140
  (tool) => !isConfirmedDelete(tool)
23750
24141
  )
23751
24142
  );
24143
+ var GEMINI_CLI_CHECKED_VERSION = "0.62.0";
24144
+ var GEMINI_ADMIN_POLICY_FILES = Object.freeze({
24145
+ rules: "remembrance.toml",
24146
+ fallback: "remembrance-fallback.toml"
24147
+ });
23752
24148
  var json = (value) => JSON.stringify(value, null, 2);
23753
24149
  var approveTables = (server, names = tools) => names.map((tool) => `[${server}.tools.${tool}]
23754
24150
  approval_mode = "approve"`).join("\n\n");
23755
- var geminiRule = (tool, decision = "allow") => `[[rule]]
23756
- mcpName = "remembrance"
23757
- toolName = "${tool}"
23758
- decision = "${decision}"
23759
- priority = 200`;
24151
+ var geminiRule = (tool, decision = "allow", priority = 200) => [
24152
+ "[[rule]]",
24153
+ 'mcpName = "remembrance"',
24154
+ `toolName = "${tool}"`,
24155
+ ...decision === "allow" ? ["toolAnnotations = { destructiveHint = false }"] : [],
24156
+ `decision = "${decision}"`,
24157
+ `priority = ${priority}`
24158
+ ].join("\n");
24159
+ var geminiFullNameAsk = (tool) => `[[rule]]
24160
+ toolName = "mcp_remembrance_${tool}"
24161
+ decision = "ask_user"
24162
+ priority = 150`;
24163
+ var geminiFullNameAsks = (names) => names.map(
24164
+ (tool, index) => index === 0 ? [
24165
+ "# Every tool again by the full name Gemini CLI also checks calls by,",
24166
+ "# only ever asking. The allow rules above outrank them, so those tools",
24167
+ "# still run in every mode, plan mode over ACP included, and both",
24168
+ "# confirmed-delete tools ask in every mode, YOLO included.",
24169
+ geminiFullNameAsk(tool)
24170
+ ].join("\n") : geminiFullNameAsk(tool)
24171
+ );
23760
24172
  var claudeCodePluginTools = withCapture.map(
23761
24173
  (tool) => `mcp__plugin_remembrance_remembrance__${tool}`
23762
24174
  );
@@ -23829,7 +24241,12 @@ var PRIVATE_SUBMISSION_APPROVAL_SNIPPETS = Object.freeze({
23829
24241
  geminiCli: [
23830
24242
  ...tools.map((tool) => geminiRule(tool)),
23831
24243
  `${localOnlyComment}
23832
- ${geminiRule(capture)}`
24244
+ ${geminiRule(capture)}`,
24245
+ ...geminiFullNameAsks([
24246
+ ...tools,
24247
+ capture,
24248
+ ...PRIVATE_SUBMISSION_CONFIRMED_DELETE_TOOLS
24249
+ ])
23833
24250
  ].join("\n\n"),
23834
24251
  // The managed recipe's admin policy file. It holds the step's own rules
23835
24252
  // above exactly once, so administrators use it instead of them.
@@ -23838,15 +24255,26 @@ ${geminiRule(capture)}`
23838
24255
  "# One exact rule per tool in includeTools: allow, except the two",
23839
24256
  "# confirmed-delete tools, which ask. To make a tool ask, change its",
23840
24257
  '# decision to "ask_user" rather than deleting its rule: an admin ask',
23841
- "# outranks users' own allow rules, and without one a user's allow decides."
24258
+ "# outranks users' own allow rules, and without one a user's allow decides.",
24259
+ "# Keep each allow rule's toolAnnotations line: it stops the rule from also",
24260
+ "# allowing another server's tool that has the same full name."
23842
24261
  ].join("\n"),
23843
24262
  ...REMEMBRANCE_MCP_RECOMMENDED_LOCAL_ORG_TOOLS.map((tool) => {
23844
24263
  if (isConfirmedDelete(tool)) return geminiRule(tool, "ask_user");
23845
24264
  if (tool === capture) return `${localOnlyComment}
23846
24265
  ${geminiRule(tool)}`;
23847
24266
  return geminiRule(tool);
23848
- })
23849
- ].join("\n\n")
24267
+ }),
24268
+ ...geminiFullNameAsks(REMEMBRANCE_MCP_RECOMMENDED_LOCAL_ORG_TOOLS)
24269
+ ].join("\n\n"),
24270
+ // Only where mcp.allowed lists Remembrance, which allows every tool of the
24271
+ // server: this admin ask outranks that allow for each tool without its own
24272
+ // rule above, and those rules, at priority 200, still win for their tools.
24273
+ geminiCliAdminFallback: [
24274
+ `# Save as its own file, ${GEMINI_ADMIN_POLICY_FILES.fallback}, only where`,
24275
+ "# mcp.allowed lists Remembrance; keep toolName, or Gemini CLI skips the file.",
24276
+ geminiRule("*", "ask_user", 100)
24277
+ ].join("\n")
23850
24278
  });
23851
24279
 
23852
24280
  // ../core/src/private-skill-completion.ts
@@ -23895,6 +24323,455 @@ var privateSkillCompletionContinuationSchema = external_exports.discriminatedUni
23895
24323
  continuation.extend({ operation: external_exports.literal("resume"), mode: external_exports.literal("changed_revision"), deadline_at: external_exports.number().int().positive() }).strict()
23896
24324
  ]);
23897
24325
 
24326
+ // ../core/src/verifier.ts
24327
+ var duplicateCandidateSchema = external_exports.object({
24328
+ type: external_exports.enum(["skill", "resource", "remembrance"]),
24329
+ id: external_exports.string().min(1).max(MAX_SHORT_TEXT_LENGTH),
24330
+ slug: external_exports.string().min(1).max(MAX_SHORT_TEXT_LENGTH).optional(),
24331
+ similarity: external_exports.number().min(0).max(1)
24332
+ });
24333
+ var PROPOSED_METADATA_MAX_KEYWORDS = 25;
24334
+ var PROPOSED_METADATA_MAX_TAGS = 15;
24335
+ var PROPOSED_METADATA_MAX_DOMAINS = 8;
24336
+ var PROPOSED_METADATA_MAX_TERM_LENGTH = 64;
24337
+ var PROPOSED_METADATA_MAX_RATIONALE_LENGTH = 2e3;
24338
+ var PROPOSED_METADATA_MAX_MODEL_LENGTH = MAX_SHORT_TEXT_LENGTH;
24339
+ var LOW_VALUE_PROPOSED_METADATA_EXACT_TERMS = /* @__PURE__ */ new Set([
24340
+ "agent",
24341
+ "agents",
24342
+ "agent-skill",
24343
+ "agent-skills",
24344
+ "backfill",
24345
+ "candidate",
24346
+ "candidates",
24347
+ "leaderboard",
24348
+ "import",
24349
+ "imported",
24350
+ "rank",
24351
+ "ranking",
24352
+ "skill",
24353
+ "skills",
24354
+ "skills-sh",
24355
+ "skill-candidate",
24356
+ "skill-candidates"
24357
+ ]);
24358
+ var LOW_VALUE_PROPOSED_METADATA_PATTERNS = [
24359
+ /\bagent\s+skills?\b/i,
24360
+ /\bagentspace\b/i,
24361
+ /\bskill\s+candidates?\b/i,
24362
+ /\bskills?[\s.-]*sh\b/i,
24363
+ /\bleaderboard\s+rank\b/i,
24364
+ /\bnpx\s+skills\s+add\b/i
24365
+ ];
24366
+ function sanitizeProposedMetadataTerm(value) {
24367
+ if (typeof value !== "string") {
24368
+ return null;
24369
+ }
24370
+ const trimmed = value.trim().slice(0, PROPOSED_METADATA_MAX_TERM_LENGTH);
24371
+ if (!trimmed) {
24372
+ return null;
24373
+ }
24374
+ const normalized2 = trimmed.toLowerCase().replace(/[_/.]+/g, "-").replace(/\s+/g, " ").replace(/^-+|-+$/g, "");
24375
+ if (LOW_VALUE_PROPOSED_METADATA_EXACT_TERMS.has(normalized2)) {
24376
+ return null;
24377
+ }
24378
+ if (LOW_VALUE_PROPOSED_METADATA_PATTERNS.some(
24379
+ (pattern) => pattern.test(trimmed)
24380
+ )) {
24381
+ return null;
24382
+ }
24383
+ return trimmed;
24384
+ }
24385
+ var proposedMetadataTermArraySchema = (max) => external_exports.preprocess(
24386
+ (value) => {
24387
+ if (!Array.isArray(value)) {
24388
+ return value;
24389
+ }
24390
+ const seen = /* @__PURE__ */ new Set();
24391
+ const terms = [];
24392
+ for (const entry of value) {
24393
+ const trimmed = sanitizeProposedMetadataTerm(entry);
24394
+ if (!trimmed) {
24395
+ continue;
24396
+ }
24397
+ const key = trimmed.toLowerCase();
24398
+ if (seen.has(key)) {
24399
+ continue;
24400
+ }
24401
+ seen.add(key);
24402
+ terms.push(trimmed);
24403
+ }
24404
+ return terms.slice(0, max);
24405
+ },
24406
+ external_exports.array(external_exports.string().min(1).max(PROPOSED_METADATA_MAX_TERM_LENGTH)).max(max)
24407
+ );
24408
+ var proposedSkillMetadataSchema = external_exports.object({
24409
+ keywords: proposedMetadataTermArraySchema(PROPOSED_METADATA_MAX_KEYWORDS),
24410
+ tags: proposedMetadataTermArraySchema(PROPOSED_METADATA_MAX_TAGS),
24411
+ domains: proposedMetadataTermArraySchema(PROPOSED_METADATA_MAX_DOMAINS),
24412
+ rationale: external_exports.string().trim().min(1).max(PROPOSED_METADATA_MAX_RATIONALE_LENGTH),
24413
+ model: external_exports.string().trim().min(1).max(PROPOSED_METADATA_MAX_MODEL_LENGTH)
24414
+ });
24415
+ var verifierOutputSchema = external_exports.object({
24416
+ recommended_action: verifierActionSchema,
24417
+ confidence: external_exports.number().min(0).max(1),
24418
+ duplicate_candidates: external_exports.array(duplicateCandidateSchema).max(20).default([]),
24419
+ safety_flags: external_exports.array(external_exports.string().min(1).max(MAX_SHORT_TEXT_LENGTH)).max(40).default([]),
24420
+ summary: external_exports.string().min(1).max(MAX_LONG_TEXT_LENGTH),
24421
+ proposed_patch: external_exports.string().max(MAX_LONG_TEXT_LENGTH).nullable().default(null),
24422
+ score_updates: external_exports.record(external_exports.unknown()).superRefine((value, ctx) => {
24423
+ if (serializedJsonBytes(value) > MAX_JSON_FIELD_BYTES) {
24424
+ addSerializedJsonBytesIssue(
24425
+ ctx,
24426
+ MAX_JSON_FIELD_BYTES,
24427
+ `score_updates must be ${MAX_JSON_FIELD_BYTES} bytes or smaller`
24428
+ );
24429
+ }
24430
+ }).nullable().default(null),
24431
+ // Advisory retrieval enrichment (see proposedSkillMetadataSchema). Optional
24432
+ // and defaults to null so existing verifier outputs remain valid.
24433
+ proposed_metadata: proposedSkillMetadataSchema.nullable().default(null),
24434
+ // Advisory evidence-routing assessment. Deterministic routing and the
24435
+ // existing safety/review gates decide whether it can create a candidate.
24436
+ // Topology is advisory and newer than the base verifier contract. A legacy
24437
+ // or malformed topology fragment must not discard an otherwise valid safety
24438
+ // verdict; it degrades to null, which the topology router retains as
24439
+ // evidence-only rather than allowing an unclassified mutation.
24440
+ topology_assessment: skillTopologyAssessmentSchema.nullable().default(null).catch(null)
24441
+ });
24442
+
24443
+ // ../core/src/verification-policy.ts
24444
+ var verificationReviewReasonCodeSchema = external_exports.enum([
24445
+ "safe_useful",
24446
+ "insufficient_evidence",
24447
+ "duplicate",
24448
+ "strategy_divergence",
24449
+ "quality_regression",
24450
+ "out_of_scope",
24451
+ "policy_preference",
24452
+ "sensitive_data",
24453
+ "prompt_injection",
24454
+ "malware_or_phishing",
24455
+ "spam",
24456
+ "invalid_submission",
24457
+ "unsupported_operation",
24458
+ "other"
24459
+ ]);
24460
+ var verifierAssessmentSchema = external_exports.object({
24461
+ evidence_quality: external_exports.number().min(0).max(1),
24462
+ safety_risk: external_exports.number().min(0).max(1),
24463
+ quality_confidence: external_exports.number().min(0).max(1),
24464
+ duplicate_likelihood: external_exports.number().min(0).max(1),
24465
+ applicability: external_exports.number().min(0).max(1),
24466
+ novelty: external_exports.number().min(0).max(1)
24467
+ }).strict();
24468
+ var verificationRubricPackSchema = external_exports.object({
24469
+ version: external_exports.string().min(1).max(MAX_SHORT_TEXT_LENGTH),
24470
+ evidence_standard: external_exports.enum(["strict", "balanced", "permissive"]),
24471
+ duplicate_strategy: external_exports.enum(["human", "merge_when_clear"]),
24472
+ quality_regression_tolerance: external_exports.enum(["none", "minor"]),
24473
+ external_dependency_handling: external_exports.enum(["human", "verified_only"])
24474
+ }).strict();
24475
+ var verificationPolicyVerifierOutputSchema = verifierOutputSchema.extend({
24476
+ // Existing and external approvers remain compatible when this is absent.
24477
+ assessment: verifierAssessmentSchema.nullable().default(null)
24478
+ });
24479
+ var verificationAdminReviewActionSchema = adminReviewActionSchema.extend({
24480
+ reason_code: verificationReviewReasonCodeSchema.optional(),
24481
+ topology_action: skillTopologyActionSchema.optional()
24482
+ }).superRefine((value, ctx) => {
24483
+ if (value.reason_code === "other" && !value.note) {
24484
+ ctx.addIssue({
24485
+ code: external_exports.ZodIssueCode.custom,
24486
+ message: "A note is required when the review reason is other",
24487
+ path: ["note"]
24488
+ });
24489
+ }
24490
+ if (value.topology_action && value.action !== "accept" && value.action !== "merge" && value.action !== "fork") {
24491
+ ctx.addIssue({
24492
+ code: external_exports.ZodIssueCode.custom,
24493
+ message: "A topology route may be selected only when accepting, merging, or forking the reviewed evidence",
24494
+ path: ["topology_action"]
24495
+ });
24496
+ }
24497
+ });
24498
+ var BENIGN_REVIEW_FLAGS = /* @__PURE__ */ new Set([
24499
+ "public_skill_change_requires_human_review",
24500
+ "public_skill_change_duplicate_requires_human_review",
24501
+ "public_evidence_requires_human_review",
24502
+ "score_updates_discarded"
24503
+ ]);
24504
+ var SAFE_VERIFICATION_POLICY_FLAG_CATEGORIES = /* @__PURE__ */ new Set([
24505
+ ...BENIGN_REVIEW_FLAGS,
24506
+ "verification_unavailable",
24507
+ "prompt_injection",
24508
+ "sensitive_data",
24509
+ "malware_or_phishing",
24510
+ "spam",
24511
+ "other_safety_signal"
24512
+ ]);
24513
+
24514
+ // ../core/src/admin-review-decision-contract.ts
24515
+ var identifier = external_exports.string().min(1).max(MAX_SHORT_TEXT_LENGTH);
24516
+ var nullableIdentifier = identifier.nullable();
24517
+ var timestamp = external_exports.string().datetime();
24518
+ var targetTypes = external_exports.enum([
24519
+ "remembrance",
24520
+ "resource",
24521
+ "resource_review",
24522
+ "skill_idea",
24523
+ "suggestion"
24524
+ ]);
24525
+ var reviewDecisionPreviewSelectorSchema = external_exports.object({
24526
+ action: adminReviewActionValueSchema.nullable().default(null),
24527
+ topology_action: skillTopologyActionSchema.nullable().default(null),
24528
+ reason_code: verificationReviewReasonCodeSchema.nullable().default(null)
24529
+ }).strict().superRefine((value, ctx) => {
24530
+ if (value.topology_action && !["accept", "merge", "fork"].includes(value.action ?? "")) {
24531
+ ctx.addIssue({
24532
+ code: external_exports.ZodIssueCode.custom,
24533
+ path: ["topology_action"],
24534
+ message: "A topology route requires an accepting, merging, or forking preview."
24535
+ });
24536
+ }
24537
+ });
24538
+ var overlayRevisionSchema = external_exports.object({
24539
+ id: identifier,
24540
+ status: identifier,
24541
+ version: identifier,
24542
+ revision: external_exports.number().int().nonnegative().nullable(),
24543
+ updated_at: timestamp,
24544
+ private_content_ref: nullableIdentifier,
24545
+ private_catalog_ref: nullableIdentifier,
24546
+ private_catalog_revision_id: nullableIdentifier,
24547
+ private_catalog_version_id: nullableIdentifier,
24548
+ evolution_mode: nullableIdentifier
24549
+ }).strict();
24550
+ var skillRevisionSchema = external_exports.object({
24551
+ id: identifier,
24552
+ slug: identifier,
24553
+ status: identifier,
24554
+ visibility: identifier,
24555
+ version: identifier,
24556
+ current_version_id: nullableIdentifier,
24557
+ updated_at: timestamp
24558
+ }).strict();
24559
+ var versionRevisionSchema = external_exports.object({
24560
+ id: identifier,
24561
+ skill_id: identifier,
24562
+ version: identifier,
24563
+ status: identifier,
24564
+ updated_at: timestamp,
24565
+ private_content_ref: nullableIdentifier,
24566
+ private_content_revision_id: nullableIdentifier,
24567
+ private_content_org_id: nullableIdentifier
24568
+ }).strict();
24569
+ var consumedBaselineSchema = external_exports.object({
24570
+ kind: external_exports.enum(["bundled_seed", "skill_metadata", "public_sync"]),
24571
+ digest: identifier
24572
+ }).strict();
24573
+ var reviewDecisionSnapshotSchema = external_exports.object({
24574
+ schema_version: external_exports.literal("admin-review-decision-snapshot-v1"),
24575
+ org_id: identifier,
24576
+ public_skill_access_policy: external_exports.enum(["allow", "org_only"]),
24577
+ selected_route: reviewDecisionPreviewSelectorSchema,
24578
+ actor: external_exports.object({
24579
+ type: identifier,
24580
+ id: identifier,
24581
+ org_id: identifier,
24582
+ api_key_id: nullableIdentifier,
24583
+ token_id: nullableIdentifier
24584
+ }).strict(),
24585
+ job: external_exports.object({
24586
+ id: identifier,
24587
+ target_type: targetTypes,
24588
+ target_id: identifier,
24589
+ status: identifier,
24590
+ updated_at: timestamp,
24591
+ verifier_input_hash: nullableIdentifier,
24592
+ private_verification_artifact_id: nullableIdentifier,
24593
+ private_verification_result_digest: nullableIdentifier,
24594
+ private_semantic_context_ref: nullableIdentifier,
24595
+ private_context_ref: nullableIdentifier,
24596
+ private_context_revision_id: nullableIdentifier
24597
+ }).strict(),
24598
+ target: external_exports.object({
24599
+ id: identifier,
24600
+ updated_at: timestamp,
24601
+ payload_ref: nullableIdentifier,
24602
+ superseded_by_submission_id: nullableIdentifier,
24603
+ disposition_job_id: nullableIdentifier
24604
+ }).strict(),
24605
+ private_payload: external_exports.object({
24606
+ id: identifier,
24607
+ updated_at: timestamp,
24608
+ encryption_mode: identifier,
24609
+ inspection_status: nullableIdentifier,
24610
+ inspection_updated_at: timestamp.nullable(),
24611
+ inspection_projection_digest: nullableIdentifier,
24612
+ inspection_inspector_digest: nullableIdentifier
24613
+ }).strict().nullable(),
24614
+ protected_source_binding: external_exports.object({
24615
+ schema_version: external_exports.literal("protected-submission-source-v1"),
24616
+ source_type: external_exports.enum(["skill_idea", "suggestion", "remembrance"]),
24617
+ source_id: identifier,
24618
+ source_public_id: identifier,
24619
+ content_digest: identifier,
24620
+ inline_job_digest: identifier.nullable()
24621
+ }).strict().optional(),
24622
+ legacy_public_payload: external_exports.object({
24623
+ schema_version: external_exports.literal("legacy-public-remembrance-payload-v1"),
24624
+ id: identifier,
24625
+ updated_at: timestamp,
24626
+ source_public_id: identifier,
24627
+ raw_digest: identifier,
24628
+ redacted_digest: identifier,
24629
+ target_digest: identifier,
24630
+ inline_job_digest: identifier.nullable()
24631
+ }).strict().optional(),
24632
+ current_skill: external_exports.object({
24633
+ slug: identifier,
24634
+ overlay: overlayRevisionSchema.nullable(),
24635
+ version: versionRevisionSchema.nullable(),
24636
+ consumed_baseline: consumedBaselineSchema.nullable()
24637
+ }).strict().nullable(),
24638
+ source_skill: external_exports.object({
24639
+ skill: skillRevisionSchema,
24640
+ version: versionRevisionSchema.nullable(),
24641
+ consumed_baseline: consumedBaselineSchema.nullable()
24642
+ }).strict().nullable(),
24643
+ parent_skill: external_exports.object({
24644
+ skill: skillRevisionSchema,
24645
+ version: versionRevisionSchema,
24646
+ overlay: overlayRevisionSchema.nullable()
24647
+ }).strict().nullable()
24648
+ }).strict();
24649
+
24650
+ // ../core/src/review-workflows.ts
24651
+ var PRIVATE_SKILL_REVIEW_REPAIR_VERSION = "private-skill-review-repair-v1";
24652
+ var REVIEW_COMPARISON_TOOL_DESCRIPTION = "Organization admin:review only. Read complete exact source, parent and current skill versions already linked to one pending review job. Supply no action, route, organization or arbitrary skill ID. This does not select a route or grant decision authority: inspect the current review detail and its fresh snapshot separately before any decision. An unavailable, held, changed or foreign reference refuses the whole comparison; nothing is truncated or silently substituted.";
24653
+ var REVIEW_DRAFT_REPAIR_TOOL_DESCRIPTION = "Organization admin:review only; explicit delegated AI review authority, not routine learning permission. Create one complete protected replacement for a pending private skill draft using its current unselected review snapshot. Use a stable psrr_ plus 32 lowercase hex request_id; the transport sets Idempotency-Key to that exact ID. Exact replay returns the original replacement receipt; changed input under that ID conflicts. All normal secret inspection, protection, routing, verification and review checks apply. The local client requires inspection to leave the authored capture unchanged before sending. A local hold returns content-free recovery, never an alternate transport or a rewritten original. Creation preserves the original and never approves, rejects or supersedes it. Review the replacement normally, then close the original separately only after proving an accepted, tenant-readable active replacement skill. No public or cross-organization fallback.";
24654
+ var REVIEW_DRAFT_REPAIR_NEXT_INSTRUCTION = "Review the replacement normally. Keep the original open until an accepted, tenant-readable active skill version proves the replacement usable.";
24655
+ var reviewWorkflowJobIdSchema = external_exports.string().regex(/^job_[a-f0-9]{18}$/u);
24656
+ var privateSkillReviewRepairRequestIdSchema = external_exports.string().regex(/^psrr_[a-f0-9]{32}$/u);
24657
+ var referenceIdentifier = external_exports.string().min(1).max(MAX_SHORT_TEXT_LENGTH);
24658
+ var MAX_REVIEW_REFERENCE_BODY_BYTES = 1048576;
24659
+ var reviewReferenceSkillSchema = external_exports.object({
24660
+ skill_id: referenceIdentifier,
24661
+ slug: referenceIdentifier,
24662
+ version_id: referenceIdentifier,
24663
+ version: referenceIdentifier,
24664
+ skill_md: external_exports.string().min(1).max(MAX_REVIEW_REFERENCE_BODY_BYTES).refine((value) => new TextEncoder().encode(value).length <= MAX_REVIEW_REFERENCE_BODY_BYTES),
24665
+ content_hash: referenceIdentifier
24666
+ }).strict();
24667
+ var reviewReferenceComparisonSchema = external_exports.object({
24668
+ schema_version: external_exports.literal("review-reference-comparison-v1"),
24669
+ job_id: reviewWorkflowJobIdSchema,
24670
+ source_skill: reviewReferenceSkillSchema.nullable(),
24671
+ parent_skill: reviewReferenceSkillSchema.nullable(),
24672
+ current_skill: reviewReferenceSkillSchema.nullable()
24673
+ }).strict();
24674
+ function reviewWorkflowResponseBound(tool, body, request) {
24675
+ if (tool === "get_review_comparison") {
24676
+ const parsed2 = reviewReferenceComparisonSchema.safeParse(body);
24677
+ return parsed2.success && parsed2.data.job_id === request.job_id;
24678
+ }
24679
+ if (tool !== "repair_review_draft") return false;
24680
+ const parsed = external_exports.object({
24681
+ contract_version: external_exports.literal(PRIVATE_SKILL_REVIEW_REPAIR_VERSION),
24682
+ request_id: privateSkillReviewRepairRequestIdSchema,
24683
+ original_job_id: reviewWorkflowJobIdSchema,
24684
+ replacement: external_exports.object({
24685
+ public_id: external_exports.string().regex(/^ipub_[a-f0-9]{18}$/u),
24686
+ job_id: reviewWorkflowJobIdSchema,
24687
+ status: external_exports.enum(["submitted", "duplicate", "accepted", "rejected", "merged", "forked", "needs_review", "quarantined"]),
24688
+ visibility: external_exports.literal("organization_private")
24689
+ }).strict(),
24690
+ replayed: external_exports.boolean(),
24691
+ original_disposition: external_exports.literal("unchanged"),
24692
+ verification: external_exports.object({
24693
+ verification_job: external_exports.object({
24694
+ id: reviewWorkflowJobIdSchema,
24695
+ status: verificationJobStatusSchema,
24696
+ target_type: external_exports.literal("skill_idea"),
24697
+ target_id: external_exports.string().regex(/^idea_[a-f0-9]{18}$/u)
24698
+ }).strict(),
24699
+ queue: external_exports.object({ queued: external_exports.boolean(), queueJobId: reviewWorkflowJobIdSchema.nullable() }).strict()
24700
+ }).strict().nullable(),
24701
+ verification_status: verificationJobStatusSchema,
24702
+ dispatch_state: external_exports.enum(["existing_persisted_job", "queued", "mongo_poll_fallback"]),
24703
+ next_action: external_exports.object({
24704
+ method: external_exports.literal("GET"),
24705
+ path: external_exports.literal("/api/v1/admin/review-queue"),
24706
+ query: external_exports.object({ job_id: reviewWorkflowJobIdSchema, review_provenance: external_exports.literal("delegated_ai") }).strict(),
24707
+ instruction: external_exports.literal(REVIEW_DRAFT_REPAIR_NEXT_INSTRUCTION)
24708
+ }).strict()
24709
+ }).strict().safeParse(body);
24710
+ if (!parsed.success) return false;
24711
+ const receipt = parsed.data;
24712
+ if (receipt.request_id !== request.request_id || receipt.original_job_id !== request.job_id || receipt.replacement.job_id === receipt.original_job_id || receipt.next_action.query.job_id !== receipt.replacement.job_id) return false;
24713
+ if (receipt.replayed) return receipt.verification === null && receipt.dispatch_state === "existing_persisted_job";
24714
+ const verification = receipt.verification;
24715
+ return verification !== null && verification.verification_job.id === receipt.replacement.job_id && verification.verification_job.status === receipt.verification_status && (verification.queue.queued ? receipt.dispatch_state === "queued" && verification.queue.queueJobId === receipt.replacement.job_id : receipt.dispatch_state === "mongo_poll_fallback" && verification.queue.queueJobId === null);
24716
+ }
24717
+ var reviewReferenceComparisonRequestSchema = external_exports.object({
24718
+ job_id: reviewWorkflowJobIdSchema,
24719
+ review_provenance: external_exports.literal("delegated_ai").default("delegated_ai")
24720
+ }).strict();
24721
+ function checkJsonGraph(value, context, reservedKeys) {
24722
+ const pending = [{ value, depth: 0 }];
24723
+ const seen = /* @__PURE__ */ new Set();
24724
+ let nodes = 0;
24725
+ while (pending.length) {
24726
+ const entry = pending.pop();
24727
+ if (++nodes > 1e4 || entry.depth > 32) {
24728
+ context.addIssue({ code: "custom", message: "JSON structure exceeds the bounded review request limits." });
24729
+ return false;
24730
+ }
24731
+ const current = entry.value;
24732
+ if (current === null || typeof current === "string" || typeof current === "boolean" || typeof current === "number" && Number.isFinite(current)) continue;
24733
+ if (typeof current !== "object" || seen.has(current)) {
24734
+ context.addIssue({ code: "custom", message: "Review requests must contain finite, acyclic JSON values." });
24735
+ return false;
24736
+ }
24737
+ seen.add(current);
24738
+ for (const [key, child] of Object.entries(current)) {
24739
+ if (reservedKeys && key.startsWith("_remembrance_")) {
24740
+ context.addIssue({ code: "custom", message: "Server provenance fields are reserved." });
24741
+ return false;
24742
+ }
24743
+ pending.push({ value: child, depth: entry.depth + 1 });
24744
+ }
24745
+ }
24746
+ return true;
24747
+ }
24748
+ var reviewSnapshot = reviewDecisionSnapshotSchema.superRefine((value, context) => {
24749
+ if (!checkJsonGraph(value, context, false)) return;
24750
+ if (serializedJsonBytes(value) > MAX_JSON_FIELD_BYTES) {
24751
+ addSerializedJsonBytesIssue(context, MAX_JSON_FIELD_BYTES, "Review snapshot exceeds its JSON byte limit.");
24752
+ }
24753
+ });
24754
+ var repairCapture = privateSkillCaptureSchema.superRefine((capture2, context) => {
24755
+ checkJsonGraph(capture2.proposed_metadata, context, true);
24756
+ });
24757
+ var privateSkillReviewRepairRequest = external_exports.object({
24758
+ contract_version: external_exports.literal(PRIVATE_SKILL_REVIEW_REPAIR_VERSION),
24759
+ job_id: reviewWorkflowJobIdSchema,
24760
+ request_id: privateSkillReviewRepairRequestIdSchema,
24761
+ review_provenance: external_exports.literal("delegated_ai").default("delegated_ai"),
24762
+ expected_review_snapshot: reviewSnapshot,
24763
+ capture: repairCapture
24764
+ }).strict().superRefine((value, context) => {
24765
+ if (!checkJsonGraph(value, context, false)) return;
24766
+ if (serializedJsonBytes(value) > DEFAULT_MUTATION_BODY_LIMIT_BYTES) {
24767
+ addSerializedJsonBytesIssue(context, DEFAULT_MUTATION_BODY_LIMIT_BYTES, "Review repair exceeds its JSON byte limit; nothing is truncated.");
24768
+ }
24769
+ });
24770
+ var privateSkillReviewRepairRequestSchema = external_exports.preprocess((value, context) => {
24771
+ if (!checkJsonGraph(value, context, false)) return external_exports.NEVER;
24772
+ return value;
24773
+ }, privateSkillReviewRepairRequest);
24774
+
23898
24775
  // ../core/src/seed.ts
23899
24776
  var siteUrl = "https://remembrance.dev";
23900
24777
  var feedbackUrl = `${siteUrl}/api/v1/agent/remembrances`;
@@ -24002,7 +24879,7 @@ var seedSkills = [
24002
24879
  summary: "Operational setup and troubleshooting workflow for Remembrance across Claude Code, Codex, OpenClaw, Cursor, Gemini, MCP, REST, skill-only installs, enterprise keys, and local agent identity.",
24003
24880
  status: "active",
24004
24881
  visibility: "public",
24005
- version: "0.1.39",
24882
+ version: "0.1.40",
24006
24883
  domains: ["agent-skills", "mcp", "resource-discovery"],
24007
24884
  tags: [
24008
24885
  "remembrance",
@@ -24053,7 +24930,7 @@ var seedSkills = [
24053
24930
  "gemini",
24054
24931
  "rest"
24055
24932
  ],
24056
- version: "0.1.39",
24933
+ version: "0.1.40",
24057
24934
  status: "active",
24058
24935
  visibility: "public",
24059
24936
  providers: ["codex", "claude", "cursor", "openclaw", "generic"],
@@ -24242,22 +25119,26 @@ claude plugin install remembrance@remembrance
24242
25119
 
24243
25120
  Codex:
24244
25121
 
25122
+ **Codex CLI.** The Codex plugin needs a Codex CLI: \`codex\` on your PATH or, on
25123
+ macOS, the CLI bundled in the ChatGPT desktop app. The setup, update and
25124
+ hook-review commands run the newest one they find, so an older \`codex\` on PATH
25125
+ cannot shadow the app's newer CLI; set \`CODEX_CLI\` to a CLI's full path to
25126
+ choose one yourself. No other host needs the Codex CLI.
25127
+
24245
25128
  ~~~bash
24246
- CODEX_CLI="\${CODEX_CLI:-$(command -v codex || true)}"
24247
- [ -x "$CODEX_CLI" ] || CODEX_CLI="/Applications/ChatGPT.app/Contents/Resources/codex"
24248
- [ -x "$CODEX_CLI" ] || CODEX_CLI="/Applications/Codex.app/Contents/Resources/codex"
24249
- [ -x "$CODEX_CLI" ] || { printf '%s\\n' "Codex CLI not found. Install the Codex CLI, or install or update the ChatGPT desktop app on macOS, then try again." >&2; exit 1; }
24250
- "$CODEX_CLI" plugin marketplace add dreamarkinc/remembrance-skills &&
24251
- "$CODEX_CLI" plugin marketplace upgrade remembrance &&
24252
- "$CODEX_CLI" plugin add remembrance@remembrance &&
24253
- "$CODEX_CLI"
25129
+ ${CODEX_PLUGIN_SETUP_COMMAND}
24254
25130
  ~~~
24255
25131
 
24256
25132
  This command handles both first install and update. If zsh says
24257
- "codex: command not found", it discovers the current ChatGPT desktop bundle or
24258
- the legacy Codex app bundle without requiring a shell alias. The final command
24259
- opens Codex CLI so its secure hook review can be completed immediately when
24260
- Codex requires it.
25133
+ "codex: command not found", it still finds the CLI bundled in the ChatGPT
25134
+ desktop app without requiring a shell alias. The final command opens Codex CLI
25135
+ so its secure hook review can be completed immediately when Codex requires it.
25136
+
25137
+ The block runs in a subshell, so a failure prints a message and leaves your
25138
+ terminal open. It uses \`CODEX_CLI\` when set; otherwise it runs the newest of
25139
+ \`codex\` on PATH, the ChatGPT desktop app's bundled CLI
25140
+ (\`/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex\`) and the
25141
+ older bundle paths, and stops at the first failed step.
24261
25142
 
24262
25143
  Codex will not execute plugin hooks until their exact definitions are trusted.
24263
25144
  In the Codex window opened by the installer, if Codex shows a **Hooks need
@@ -24442,6 +25323,39 @@ only the capture is reviewed; its submission still must not prompt.
24442
25323
  \`run_connection_doctor\` cannot see a persisted approval; its \`host_approval\`
24443
25324
  field reports only recent denials.
24444
25325
 
25326
+ ### Unattended runs
25327
+
25328
+ A run no person attends, such as a scheduled job, \`codex exec\` or
25329
+ \`claude -p\`, cannot answer the user decisions the hooks ask about retained
25330
+ private drafts: deliver, keep or delete. To keep its learning going without
25331
+ using those decisions up:
25332
+
25333
+ 1. Approve the four private submit and retry tools as above, so the run
25334
+ delivers its own lessons and skills. On a host that asks, a run nobody can
25335
+ answer denies them, and the draft waits in the outbox.
25336
+ 2. Start the run with \`REMEMBRANCE_UNATTENDED=1\`. Its hooks then show none of
25337
+ the user decisions (drafts awaiting the user, held drafts, parked drafts
25338
+ coming back), so none is used up, and the next prompt a person makes on the
25339
+ machine gets them. The run still captures and delivers its own lessons,
25340
+ and nothing about the drafts changes.
25341
+ - Codex: \`REMEMBRANCE_UNATTENDED=1 codex exec ...\`.
25342
+ - Claude Code: \`REMEMBRANCE_UNATTENDED=1 claude -p ...\`, or
25343
+ \`{"env":{"REMEMBRANCE_UNATTENDED":"1"}}\` in settings only those runs
25344
+ load: \`--settings\`, or \`.claude/settings.local.json\` in a folder only
25345
+ scheduled runs use.
25346
+ - OpenCode: \`REMEMBRANCE_UNATTENDED=1 opencode run ...\`. A run attached
25347
+ to a server that is already running follows that server's environment.
25348
+ - Cursor and VS Code: the environment the app or CLI starts its hooks
25349
+ with. Cursor asks these decisions only with
25350
+ \`REMEMBRANCE_VISIBLE_COMPLETION_RECOVERY=1\`.
25351
+ - OpenClaw: the Gateway's environment. It then applies to every session
25352
+ that Gateway serves, so set it only on a Gateway or profile that serves
25353
+ no person.
25354
+
25355
+ Leave \`REMEMBRANCE_UNATTENDED\` unset for sessions a person uses. Do not set
25356
+ \`REMEMBRANCE_AUTO_CONTRIBUTE=0\` for this instead: it also stops the run's own
25357
+ learning.
25358
+
24445
25359
  ### Claude Code
24446
25360
 
24447
25361
  Merge these entries into \`permissions.allow\` in \`~/.claude/settings.json\`,
@@ -24585,21 +25499,54 @@ mixed-version installs, use allow-always.
24585
25499
 
24586
25500
  ### Gemini CLI
24587
25501
 
24588
- Create \`~/.gemini/policies/remembrance.toml\` with one rule per tool; the last
24589
- rule is the local-only \`capture_learning\` entry:
25502
+ Create \`~/.gemini/policies/remembrance.toml\` with one allow rule per tool, the
25503
+ last of them the local-only \`capture_learning\` entry, then one ask rule for
25504
+ each of those tools and for both confirmed-delete tools, by the full names
25505
+ Gemini CLI gives them:
24590
25506
 
24591
25507
  ~~~toml
24592
25508
  ${PRIVATE_SUBMISSION_APPROVAL_SNIPPETS.geminiCli}
24593
25509
  ~~~
24594
25510
 
24595
- Gemini CLI asks before every MCP tool without an allow rule, and
24596
- non-interactive runs treat that prompt as a denial. These rules cover private
24597
- learning only, so a headless run also needs rules for the other Remembrance
24598
- tools it calls, such as \`query_skills\`. Keep \`trust\` false and do not list
24599
- the server in \`mcp.allowed\`: Gemini CLI turns \`trust: true\` and an
24600
- \`mcp.allowed\` entry alike into an allow rule for every tool of the server.
24601
- Administrators use the admin policy file in "Approve Gemini CLI" instead, which
24602
- already contains these rules.
25511
+ Without a rule, Gemini CLI asks before a Remembrance tool in its default
25512
+ and auto-edit modes; YOLO mode runs the tool without asking, and plan mode
25513
+ blocks it or, for a read-only tool, asks. A headless run, such as
25514
+ \`gemini -p\`, cannot ask: the model never sees a tool that no rule covers, and
25515
+ a tool whose rule asks is denied. These rules cover private learning only, so a
25516
+ headless run also needs rules for the other Remembrance tools it calls, such as
25517
+ \`query_skills\`. The rules name no approval mode, so they also apply in plan
25518
+ mode: there the five tools run without a prompt, private submissions included.
25519
+
25520
+ Gemini CLI also checks some calls under the server name \`mcp_remembrance\`,
25521
+ which no rule with \`mcpName = "remembrance"\` matches: in an IDE connected
25522
+ over ACP, before any other check, and in the terminal, after a rule asks. There
25523
+ only the rules that name a tool by its full name, \`mcp_remembrance_<tool>\`,
25524
+ match, and they only ask. In plan mode over ACP, that ask hands the call on to
25525
+ the allow rules, so the five tools run; without it, plan mode denies them. Both
25526
+ delete tools ask in every mode, YOLO included, whether Gemini CLI starts with
25527
+ \`--yolo\` or the user turns it on with Ctrl+Y; without their full-name rules,
25528
+ YOLO mode runs both without asking. Never change a full-name rule to allow: a
25529
+ rule without \`mcpName\` also matches another server's tool that has the same
25530
+ full name, such as the tool \`private_lesson_candidate\` of a server named
25531
+ \`remembrance_submit\`.
25532
+
25533
+ Each allow rule also requires \`destructiveHint = false\`, which Remembrance's
25534
+ server declares for every tool except the two delete tools. Gemini CLI checks a
25535
+ subagent's calls without the server name or the tool's annotations, and takes
25536
+ the server name from the full name, so without that condition an allow rule
25537
+ would also let a subagent run such a look-alike tool without asking; with it,
25538
+ the full-name rule makes that call ask. A user's own "Allow tool for this
25539
+ session" or "Allow all server tools for this session" answer still stops the
25540
+ prompts until Gemini CLI restarts.
25541
+
25542
+ Keep \`trust\` false and do not list the server in \`mcp.allowed\`: Gemini CLI
25543
+ turns \`trust: true\` and an \`mcp.allowed\` entry alike into an allow rule for
25544
+ every tool of the server. A \`--policy\` flag or a \`policyPaths\` setting
25545
+ replaces \`~/.gemini/policies\`, and Gemini CLI then does not read this file.
25546
+ Gemini CLI starts MCP servers only in a trusted folder; "Approve Gemini CLI"
25547
+ covers unattended runs. Administrators use the admin policy file in "Approve
25548
+ Gemini CLI" instead, which already contains these rules. Checked against Gemini
25549
+ CLI ${GEMINI_CLI_CHECKED_VERSION}.
24603
25550
 
24604
25551
  ### Claude Desktop and other MCP clients
24605
25552
 
@@ -24692,8 +25639,12 @@ memory, encrypts only the canonical safe record in a local outbox, and returns
24692
25639
  a draft ID. It never writes the original input to disk, logs, telemetry, or
24693
25640
  error output. Tags
24694
25641
  use an open, bounded lowercase slug vocabulary; new technical terms survive,
24695
- while malformed or privacy-sensitive tags hold the draft instead of being
24696
- silently removed.
25642
+ while a malformed or privacy-sensitive tag is dropped and counted. Each
25643
+ redaction match becomes its marker and the lesson continues; only a stack
25644
+ trace or zero-width or bidirectional control characters hold the draft
25645
+ locally. A draft an earlier client held that the current check would send is
25646
+ offered to the user once to deliver, keep, or delete; only the user's choice
25647
+ delivers it.
24697
25648
 
24698
25649
  The plugin then calls \`submit_private_lesson_candidate\` with that draft ID.
24699
25650
  This is the host-visible network action in the flow, and
@@ -24795,6 +25746,17 @@ requirements also carry an \`mcp_servers\` allowlist, approve this server by its
24795
25746
  configured command (\`sh\`): Codex disables a server whose name and identity do
24796
25747
  not match an approved entry.
24797
25748
 
25749
+ Codex checks only a server's name and how it is launched, never the plugin's
25750
+ files. The string form, \`identity = { command = "sh" }\`, compares the command
25751
+ alone; the structured form also compares each positional argument, but neither
25752
+ inspects the working directory or environment. So another local server with
25753
+ the same name and identity, such as one a user adds to their own
25754
+ \`config.toml\`, can pass the same check; the marketplace source restriction is
25755
+ what limits where the plugin itself comes from. OpenAI's managed-configuration
25756
+ documentation does not say whether a plugin's bundled server is checked
25757
+ against \`plugins.<plugin>.mcp_servers.<server>\` entries, top-level
25758
+ \`mcp_servers\` entries, or both.
25759
+
24798
25760
  Add these entries to \`requirements.toml\`:
24799
25761
 
24800
25762
  ~~~toml
@@ -25055,9 +26017,10 @@ work. See the official
25055
26017
 
25056
26018
  ### Approve Gemini CLI
25057
26019
 
25058
- Define the canonical server and its tool allowlist in the system override
25059
- settings, not only user or workspace settings. Keep \`trust\` false;
25060
- \`trust: true\` bypasses every confirmation for the server:
26020
+ This recipe was checked against Gemini CLI ${GEMINI_CLI_CHECKED_VERSION}; check it again
26021
+ after upgrading Gemini CLI. Define the canonical server and its tool allowlist
26022
+ in the system override settings, not only user or workspace settings. Keep
26023
+ \`trust\` false; \`trust: true\` bypasses every confirmation for the server:
25061
26024
 
25062
26025
  ~~~json
25063
26026
  {
@@ -25079,50 +26042,151 @@ ${geminiIncludeToolJson}
25079
26042
  ~~~
25080
26043
 
25081
26044
  Approve tools only with exact per-tool policy rules. Do not list the server in
25082
- \`mcp.allowed\`: the server runs without it, and current Gemini CLI source turns
25083
- each \`mcp.allowed\` entry into an allow rule for every tool of that server.
25084
- Instead, save this file as \`remembrance.toml\` in the admin policy folder:
25085
- \`/Library/Application Support/GeminiCli/policies\` on macOS,
26045
+ \`mcp.allowed\`: the server runs without it, and Gemini CLI turns each
26046
+ \`mcp.allowed\` entry into an allow rule for every tool of that server.
26047
+ Instead, save this file as \`${GEMINI_ADMIN_POLICY_FILES.rules}\` in the admin policy
26048
+ folder: \`/Library/Application Support/GeminiCli/policies\` on macOS,
25086
26049
  \`/etc/gemini-cli/policies\` on Linux, or \`C:\\ProgramData\\gemini-cli\\policies\`
25087
- on Windows. Gemini CLI ignores admin policy files that are not root-owned.
26050
+ on Windows.
25088
26051
 
25089
26052
  ~~~toml
25090
26053
  ${PRIVATE_SUBMISSION_APPROVAL_SNIPPETS.geminiCliAdmin}
25091
26054
  ~~~
25092
26055
 
26056
+ Gemini CLI checks the folder, not the files in it. On macOS and Linux the
26057
+ folder must be owned by root and not writable by group or others. On Windows it
26058
+ must be owned by Administrators, SYSTEM or a system service, and only those may
26059
+ have write access to it, so remove any write access for Users, such as rights
26060
+ inherited from \`C:\\ProgramData\`. Otherwise Gemini CLI skips the whole folder
26061
+ with a security warning. It loads only regular \`.toml\` files, not symbolic
26062
+ links, and checks neither the files' owner nor the parent folders, so keep
26063
+ those owned and writable only by administrators as well. Once the folder holds
26064
+ a \`.toml\` file, Gemini CLI ignores \`--admin-policy\` and \`adminPolicyPaths\`,
26065
+ with a warning.
26066
+
25093
26067
  The file has one exact rule for every tool in \`includeTools\`: an allow rule
25094
26068
  for each tool except the two confirmed-delete tools, whose admin \`ask_user\`
25095
- rules keep them asking even where a user allowed them, so a headless run denies
25096
- them. Apart from those two, this reproduces the earlier behavior of this
25097
- recipe, whose \`mcp.allowed\` entry let every included tool run, with exact
25098
- rules instead of a whole-server rule. The file already contains the rules from
25099
- "Highly Recommended: approve private submissions" for the four private submit
25100
- and retry tools and the local-only \`capture_learning\`, so do not add those
25101
- again. To make a tool ask, change its rule to \`decision = "ask_user"\` instead
25102
- of deleting the rule: an admin-tier ask outranks users' own allow rules, while
25103
- without an admin rule a user's allow rule decides. A headless run then denies
25104
- that tool.
26069
+ rules make them ask even where a user's own rule allows them, so a headless run
26070
+ denies them. In Gemini CLI's default, auto-edit and YOLO modes, this reproduces
26071
+ the earlier behavior of this recipe, whose \`mcp.allowed\` entry let every
26072
+ included tool run, apart from those two, with exact rules instead of a
26073
+ whole-server rule. Unlike that entry, the rules name no approval mode, so they
26074
+ also apply in plan mode: there the allowed Remembrance tools run as well,
26075
+ private submissions included, and the two delete tools still ask. The file
26076
+ already contains the rules from "Highly Recommended: approve private
26077
+ submissions" for the four private submit and retry tools and the local-only
26078
+ \`capture_learning\`, so do not add those again. To make a tool ask, change its
26079
+ rule to \`decision = "ask_user"\` instead of deleting the rule: an admin-tier ask
26080
+ outranks users' own allow rules, while without an admin rule a user's allow
26081
+ rule decides. A headless run then denies that tool.
26082
+
26083
+ The rules after those name every tool in \`includeTools\` again by the full
26084
+ name Gemini CLI gives it, \`mcp_remembrance_<tool>\`, without \`mcpName\`, and
26085
+ only ask. Gemini CLI ${GEMINI_CLI_CHECKED_VERSION} also checks calls under the server
26086
+ name \`mcp_remembrance\`, which no rule with \`mcpName = "remembrance"\`
26087
+ matches: in an IDE connected over ACP before any other check, and in the
26088
+ terminal after a rule asks. Without a full-name rule, the mode's own default
26089
+ decides there: plan mode denies every tool not marked read-only, and YOLO mode
26090
+ allows every tool. With them, that check only asks. Over ACP it then hands the
26091
+ call on to the exact rules, so the allowed tools run in plan mode as well, and
26092
+ both delete tools ask in every approval mode, YOLO included, whether Gemini
26093
+ CLI started with \`--yolo\` or the user turned it on with Ctrl+Y, while a
26094
+ headless run refuses them. Never change them to allow: without \`mcpName\`, a
26095
+ rule also matches another server's tool that has the same full name, such as
26096
+ the tool \`skills\` of a server named \`remembrance_query\`, whose full name is
26097
+ \`mcp_remembrance_query_skills\`.
26098
+
26099
+ Each allow rule also requires \`destructiveHint = false\`, which Remembrance's
26100
+ server declares for every tool except the two delete tools. Gemini CLI checks a
26101
+ subagent's calls without the server name or the tool's annotations, and takes
26102
+ the server name from the full name, so without that condition the allow rule
26103
+ for \`query_skills\` would also let a subagent run that \`skills\` tool without
26104
+ asking. With it, such a call asks, while Remembrance's own tools still run.
26105
+
26106
+ The delete tools' admin ask rules hold against users' policy rules, but not
26107
+ against a user's own answer to the prompt. After "Allow tool for this session",
26108
+ Gemini CLI does not ask before that tool again until it restarts, and "Allow
26109
+ all server tools for this session" on any Remembrance prompt does the same for
26110
+ every Remembrance tool, both deletes included. Where every delete must ask,
26111
+ also set \`security.disableAlwaysAllow\` to \`true\` in the system settings:
26112
+ Gemini CLI then offers neither answer for any tool, so each tool that asks does
26113
+ so every time.
26114
+
26115
+ To keep users out of YOLO mode altogether, also set \`security.disableYoloMode\`
26116
+ to \`true\` in the system settings. Gemini CLI then refuses to start in YOLO
26117
+ mode, in the terminal, headless or over ACP, and refuses Ctrl+Y. It does not
26118
+ stop an IDE connected over ACP from switching a running session to YOLO mode,
26119
+ so keep the full-name rules above either way.
25105
26120
 
25106
26121
  If the organization already restricts servers with \`mcp.allowed\`, Remembrance
25107
26122
  must be listed there to run, and that entry creates the whole-server allow rule.
25108
- Then also place this rule in the admin policy folder. It creates no allow rule:
25109
- admin rules outrank the one \`mcp.allowed\` creates, so a Remembrance tool
25110
- without its own admin rule asks again, while the per-tool rules above, at
25111
- priority 200, still win over it for their tools:
26123
+ Then also save this rule in the admin policy folder as its own file,
26124
+ \`${GEMINI_ADMIN_POLICY_FILES.fallback}\`, next to \`${GEMINI_ADMIN_POLICY_FILES.rules}\`. It creates no
26125
+ allow rule: admin rules outrank the one \`mcp.allowed\` creates, so a
26126
+ Remembrance tool without its own admin rule asks again, while the per-tool rules
26127
+ above, at priority 200, still win over it for their tools. Keep
26128
+ \`toolName = "*"\`, which matches every tool of the \`remembrance\` server, and
26129
+ keep the rule out of \`${GEMINI_ADMIN_POLICY_FILES.rules}\`: Gemini CLI rejects a rule
26130
+ without \`toolName\`, although its policy engine guide shows one, and an invalid
26131
+ rule makes it skip every rule in the same file.
25112
26132
 
25113
26133
  ~~~toml
25114
- [[rule]]
25115
- mcpName = "remembrance"
25116
- decision = "ask_user"
25117
- priority = 100
26134
+ ${PRIVATE_SUBMISSION_APPROVAL_SNIPPETS.geminiCliAdminFallback}
25118
26135
  ~~~
25119
26136
 
25120
26137
  System settings live at \`/Library/Application Support/GeminiCli/settings.json\`
25121
26138
  on macOS, \`/etc/gemini-cli/settings.json\` on Linux, and
25122
- \`C:\\ProgramData\\gemini-cli\\settings.json\` on Windows. Also allow
25123
- \`remembrance.dev\` in the organization's egress policy. Restart Gemini CLI,
25124
- inspect the registered server, then run \`run_connection_doctor\` and require
25125
- organization scope before contribution work. See the official
26139
+ \`C:\\ProgramData\\gemini-cli\\settings.json\` on Windows. Gemini CLI checks
26140
+ that file and every folder above it the way it checks the admin policy folder,
26141
+ on Windows \`C:\\ProgramData\` included, and skips the file with a security
26142
+ warning when one fails. System settings outrank user and workspace settings but
26143
+ are not locked: Gemini CLI reads them from whatever file
26144
+ \`GEMINI_CLI_SYSTEM_SETTINGS_PATH\` names, so a user who controls the
26145
+ environment it starts in can drop this definition and use their own, for
26146
+ example without \`includeTools\` or with \`trust: true\`, which in a trusted
26147
+ folder also skips the admin ask rules. The admin policy folder cannot be moved
26148
+ that way. Where this matters, start Gemini CLI through a wrapper that sets the
26149
+ variable to the managed file, as Gemini CLI's enterprise guide describes.
26150
+
26151
+ The system settings also do not cover the MCP servers a subagent defines for
26152
+ itself, or the server list an IDE sends when it opens a session over ACP.
26153
+ Either can define its own server named \`remembrance\` that runs another
26154
+ command, without \`includeTools\`, and Gemini CLI ${GEMINI_CLI_CHECKED_VERSION} then
26155
+ applies the allow rules to that server's tools of the same names. A subagent
26156
+ definition in \`~/.gemini/agents\`, or one the user accepts from a trusted
26157
+ project's \`.gemini/agents\` folder, can also set \`trust: true\`, and that
26158
+ subagent then runs both delete tools without asking: in the terminal in every
26159
+ mode except plan mode, which does not run it, and over ACP in YOLO mode. An
26160
+ IDE's server list cannot set \`trust\`, so both delete tools still ask there.
26161
+ Where every delete must ask, also set \`experimental.enableAgents\` to
26162
+ \`false\` in the system settings. Gemini CLI then loads no subagents, its
26163
+ built-in ones included.
26164
+
26165
+ This recipe was not tested on Windows. A default Windows install may let the
26166
+ Users group create files and folders in \`C:\\ProgramData\`. If it does, Gemini
26167
+ CLI ${GEMINI_CLI_CHECKED_VERSION} skips \`C:\\ProgramData\\gemini-cli\\settings.json\` on
26168
+ every machine, and the admin policy folder too unless its inherited Users
26169
+ rights are removed. To check, run \`icacls C:\\ProgramData\` and
26170
+ \`icacls C:\\ProgramData\\gemini-cli\`: Gemini CLI accepts write, append,
26171
+ delete, ownership or permission rights, such as \`(W)\`, \`(WD)\`, \`(AD)\`,
26172
+ \`(M)\` or \`(F)\`, only for Administrators, SYSTEM, service accounts
26173
+ (\`NT SERVICE\\...\`), CREATOR OWNER and CREATOR GROUP. When a check fails,
26174
+ Gemini CLI's security warning names the folder and the groups that can write
26175
+ to it.
26176
+
26177
+ Gemini CLI fills in \`\${REMEMBRANCE_API_KEY}\` from the environment it starts
26178
+ in. Without that variable the server receives an empty key and uses the shared
26179
+ config file from "Enterprise/org key setup" instead. Gemini CLI starts MCP
26180
+ servers only in a trusted folder, and interactive Gemini CLI asks whether to
26181
+ trust a new folder. In a folder that is not trusted, the Remembrance server does
26182
+ not start, and a headless run, such as \`gemini -p\` in CI, exits with an error
26183
+ unless the folder is trusted, \`--skip-trust\` is passed, or
26184
+ \`GEMINI_CLI_TRUST_WORKSPACE=true\` is set. Use those two only for unattended
26185
+ runs in folders the organization trusts.
26186
+
26187
+ Also allow \`remembrance.dev\` in the organization's egress policy. Restart
26188
+ Gemini CLI, inspect the registered server, then run \`run_connection_doctor\`
26189
+ and require organization scope before contribution work. See the official
25126
26190
  [enterprise configuration](https://geminicli.com/docs/cli/enterprise/),
25127
26191
  [MCP settings](https://geminicli.com/docs/tools/mcp-server/), and
25128
26192
  [policy engine](https://geminicli.com/docs/reference/policy-engine/).
@@ -25486,9 +26550,10 @@ session skills.
25486
26550
  standing instructions proactively. If tools are still not visible, use the
25487
26551
  REST fallback and emit REMEMBRANCE_SUBMISSION_PAYLOAD only when the API is
25488
26552
  unavailable.
25489
- - "codex: command not found": use the complete Codex setup above. It checks
25490
- the current "/Applications/ChatGPT.app/Contents/Resources/codex" bundle,
25491
- then the legacy "/Applications/Codex.app/Contents/Resources/codex" path.
26553
+ - "codex: command not found": use the complete Codex setup above. It runs the
26554
+ newest Codex CLI it finds: \`codex\` on PATH, the ChatGPT desktop app's
26555
+ "/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex", or the
26556
+ older bundle paths. Set CODEX_CLI to a Codex CLI's full path to choose one.
25492
26557
  - "401 or 403": the key is missing, expired, revoked, scoped to a different
25493
26558
  environment, or not visible to the agent process. Check config file vs env
25494
26559
  precedence and regenerate a key from the dashboard if needed.
@@ -26403,123 +27468,6 @@ function invalidToolArgumentsMessage(error, schema) {
26403
27468
  ).join("; ")}${more > 0 ? ` (+${more} more)` : ""}.`;
26404
27469
  }
26405
27470
 
26406
- // ../core/src/verifier.ts
26407
- var duplicateCandidateSchema = external_exports.object({
26408
- type: external_exports.enum(["skill", "resource", "remembrance"]),
26409
- id: external_exports.string().min(1).max(MAX_SHORT_TEXT_LENGTH),
26410
- slug: external_exports.string().min(1).max(MAX_SHORT_TEXT_LENGTH).optional(),
26411
- similarity: external_exports.number().min(0).max(1)
26412
- });
26413
- var PROPOSED_METADATA_MAX_KEYWORDS = 25;
26414
- var PROPOSED_METADATA_MAX_TAGS = 15;
26415
- var PROPOSED_METADATA_MAX_DOMAINS = 8;
26416
- var PROPOSED_METADATA_MAX_TERM_LENGTH = 64;
26417
- var PROPOSED_METADATA_MAX_RATIONALE_LENGTH = 2e3;
26418
- var PROPOSED_METADATA_MAX_MODEL_LENGTH = MAX_SHORT_TEXT_LENGTH;
26419
- var LOW_VALUE_PROPOSED_METADATA_EXACT_TERMS = /* @__PURE__ */ new Set([
26420
- "agent",
26421
- "agents",
26422
- "agent-skill",
26423
- "agent-skills",
26424
- "backfill",
26425
- "candidate",
26426
- "candidates",
26427
- "leaderboard",
26428
- "import",
26429
- "imported",
26430
- "rank",
26431
- "ranking",
26432
- "skill",
26433
- "skills",
26434
- "skills-sh",
26435
- "skill-candidate",
26436
- "skill-candidates"
26437
- ]);
26438
- var LOW_VALUE_PROPOSED_METADATA_PATTERNS = [
26439
- /\bagent\s+skills?\b/i,
26440
- /\bagentspace\b/i,
26441
- /\bskill\s+candidates?\b/i,
26442
- /\bskills?[\s.-]*sh\b/i,
26443
- /\bleaderboard\s+rank\b/i,
26444
- /\bnpx\s+skills\s+add\b/i
26445
- ];
26446
- function sanitizeProposedMetadataTerm(value) {
26447
- if (typeof value !== "string") {
26448
- return null;
26449
- }
26450
- const trimmed = value.trim().slice(0, PROPOSED_METADATA_MAX_TERM_LENGTH);
26451
- if (!trimmed) {
26452
- return null;
26453
- }
26454
- const normalized2 = trimmed.toLowerCase().replace(/[_/.]+/g, "-").replace(/\s+/g, " ").replace(/^-+|-+$/g, "");
26455
- if (LOW_VALUE_PROPOSED_METADATA_EXACT_TERMS.has(normalized2)) {
26456
- return null;
26457
- }
26458
- if (LOW_VALUE_PROPOSED_METADATA_PATTERNS.some(
26459
- (pattern) => pattern.test(trimmed)
26460
- )) {
26461
- return null;
26462
- }
26463
- return trimmed;
26464
- }
26465
- var proposedMetadataTermArraySchema = (max) => external_exports.preprocess(
26466
- (value) => {
26467
- if (!Array.isArray(value)) {
26468
- return value;
26469
- }
26470
- const seen = /* @__PURE__ */ new Set();
26471
- const terms = [];
26472
- for (const entry of value) {
26473
- const trimmed = sanitizeProposedMetadataTerm(entry);
26474
- if (!trimmed) {
26475
- continue;
26476
- }
26477
- const key = trimmed.toLowerCase();
26478
- if (seen.has(key)) {
26479
- continue;
26480
- }
26481
- seen.add(key);
26482
- terms.push(trimmed);
26483
- }
26484
- return terms.slice(0, max);
26485
- },
26486
- external_exports.array(external_exports.string().min(1).max(PROPOSED_METADATA_MAX_TERM_LENGTH)).max(max)
26487
- );
26488
- var proposedSkillMetadataSchema = external_exports.object({
26489
- keywords: proposedMetadataTermArraySchema(PROPOSED_METADATA_MAX_KEYWORDS),
26490
- tags: proposedMetadataTermArraySchema(PROPOSED_METADATA_MAX_TAGS),
26491
- domains: proposedMetadataTermArraySchema(PROPOSED_METADATA_MAX_DOMAINS),
26492
- rationale: external_exports.string().trim().min(1).max(PROPOSED_METADATA_MAX_RATIONALE_LENGTH),
26493
- model: external_exports.string().trim().min(1).max(PROPOSED_METADATA_MAX_MODEL_LENGTH)
26494
- });
26495
- var verifierOutputSchema = external_exports.object({
26496
- recommended_action: verifierActionSchema,
26497
- confidence: external_exports.number().min(0).max(1),
26498
- duplicate_candidates: external_exports.array(duplicateCandidateSchema).max(20).default([]),
26499
- safety_flags: external_exports.array(external_exports.string().min(1).max(MAX_SHORT_TEXT_LENGTH)).max(40).default([]),
26500
- summary: external_exports.string().min(1).max(MAX_LONG_TEXT_LENGTH),
26501
- proposed_patch: external_exports.string().max(MAX_LONG_TEXT_LENGTH).nullable().default(null),
26502
- score_updates: external_exports.record(external_exports.unknown()).superRefine((value, ctx) => {
26503
- if (serializedJsonBytes(value) > MAX_JSON_FIELD_BYTES) {
26504
- addSerializedJsonBytesIssue(
26505
- ctx,
26506
- MAX_JSON_FIELD_BYTES,
26507
- `score_updates must be ${MAX_JSON_FIELD_BYTES} bytes or smaller`
26508
- );
26509
- }
26510
- }).nullable().default(null),
26511
- // Advisory retrieval enrichment (see proposedSkillMetadataSchema). Optional
26512
- // and defaults to null so existing verifier outputs remain valid.
26513
- proposed_metadata: proposedSkillMetadataSchema.nullable().default(null),
26514
- // Advisory evidence-routing assessment. Deterministic routing and the
26515
- // existing safety/review gates decide whether it can create a candidate.
26516
- // Topology is advisory and newer than the base verifier contract. A legacy
26517
- // or malformed topology fragment must not discard an otherwise valid safety
26518
- // verdict; it degrades to null, which the topology router retains as
26519
- // evidence-only rather than allowing an unclassified mutation.
26520
- topology_assessment: skillTopologyAssessmentSchema.nullable().default(null).catch(null)
26521
- });
26522
-
26523
27471
  // src/private-skill-protection-recovery.ts
26524
27472
  var PRIVATE_SKILL_CONFIGURATION_REFUSAL = "private_admission_configuration_error";
26525
27473
  var PRIVATE_SKILL_PERMANENT_SERVICE_REFUSAL = "private_skill_permanent_service_refusal";
@@ -28206,6 +29154,11 @@ var privateLessonInspectSchema = external_exports.object({
28206
29154
  "Zero-based local page offset. Follow next_offset until truncated is false."
28207
29155
  )
28208
29156
  }).strict();
29157
+ var privateLessonRetrySchema = privateLessonDraftReferenceSchema.extend({
29158
+ deliver_rechecked_hold: external_exports.literal(true).optional().describe(
29159
+ "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."
29160
+ )
29161
+ });
28209
29162
  var privateLessonDeleteSchema = privateLessonDraftReferenceSchema.extend({
28210
29163
  confirm: external_exports.literal(true).describe(
28211
29164
  "Must be true. Deletion is explicit and leaves a content-free tombstone."
@@ -28303,6 +29256,19 @@ var remembranceToolSchema = remembrancePayloadSchema.extend({
28303
29256
  )
28304
29257
  });
28305
29258
  var declaredToolDefinitions = [
29259
+ readTool(
29260
+ "get_review_comparison",
29261
+ REVIEW_COMPARISON_TOOL_DESCRIPTION,
29262
+ "/api/v1/admin/review-queue/comparison",
29263
+ reviewReferenceComparisonRequestSchema,
29264
+ "GET"
29265
+ ),
29266
+ contentWriteTool(
29267
+ "repair_review_draft",
29268
+ REVIEW_DRAFT_REPAIR_TOOL_DESCRIPTION,
29269
+ "/api/v1/admin/review-queue/repairs",
29270
+ privateSkillReviewRepairRequestSchema
29271
+ ),
28306
29272
  readTool(
28307
29273
  "get_connection_status",
28308
29274
  REMEMBRANCE_CONNECTION_STATUS_TOOL_DESCRIPTION,
@@ -28426,7 +29392,7 @@ var declaredToolDefinitions = [
28426
29392
  ),
28427
29393
  localTool(
28428
29394
  "prepare_private_lesson_candidate",
28429
- "Locally canonicalize, redact, validate, encrypt, and durably queue one compact organization-private failure, correction, or evidence lesson. Limits apply after local redaction: generalized_lesson at most 1200 characters and each stable_conditions item at most 240; an over-limit call is refused with the field and its length, and nothing is stored. This is an evidence lane, not a complete-skill transport: use propose_private_skill or propose_skill_idea for a complete reusable procedure, playbook, or actionable instructions. Tags use an open, bounded lowercase slug vocabulary; malformed or privacy-sensitive tags hold the draft instead of being dropped. Pre-redaction input remains memory-only and this tool performs no network request. The result returns a draft handle and never echoes lesson prose. Follow the returned next_action with submit_private_lesson_candidate; held_safety content remains local. An unsupported redactor version or digest becomes terminal superseded_redactor and is never retried or re-redacted.",
29395
+ "Locally canonicalize, redact, validate, encrypt, and durably queue one compact organization-private failure, correction, or evidence lesson. Limits apply after local redaction: generalized_lesson at most 1200 characters and each stable_conditions item at most 240; an over-limit call is refused with the field and its length, and nothing is stored. This is an evidence lane, not a complete-skill transport: use propose_private_skill or propose_skill_idea for a complete reusable procedure, playbook, or actionable instructions. Tags use an open, bounded lowercase slug vocabulary; a malformed or privacy-sensitive tag is dropped and counted. Every redaction match becomes its [redacted:category] marker and the draft continues; only a stack trace or zero-width or bidirectional control characters hold it as held_safety. Pre-redaction input remains memory-only and this tool performs no network request. The result returns a draft handle and never echoes lesson prose. Follow the returned next_action with submit_private_lesson_candidate; held_safety content remains local. An unsupported redactor version or digest becomes terminal superseded_redactor and is never retried or re-redacted.",
28430
29396
  "prepare_private_lesson_candidate",
28431
29397
  privateLessonPreparationInputSchema
28432
29398
  ),
@@ -28445,9 +29411,9 @@ var declaredToolDefinitions = [
28445
29411
  ),
28446
29412
  localNetworkTool(
28447
29413
  "retry_private_lesson_candidate",
28448
- "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; a fresh ready draft is rejected locally. It never falls back to a public or alternate transport.",
29414
+ "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.",
28449
29415
  "retry_private_lesson_candidate",
28450
- privateLessonDraftReferenceSchema,
29416
+ privateLessonRetrySchema,
28451
29417
  "content_write"
28452
29418
  ),
28453
29419
  localTool(
@@ -29052,13 +30018,13 @@ function validateServedToolDefinition(definition) {
29052
30018
  canonicalToolDefinitionForDispatch(definition);
29053
30019
  }
29054
30020
  function annotationsForTool(name) {
29055
- const readOnly = name === "list_skills" || name === "get_effective_preferences" || name === "get_value_proof" || name === "run_connection_doctor" || name === "get_private_lesson_policy" || name === "inspect_private_lesson_outbox" || name === "inspect_private_learning_outbox" || name === "get_pending_action_payload";
30021
+ const readOnly = name === "get_review_comparison" || name === "list_skills" || name === "get_effective_preferences" || name === "get_value_proof" || name === "run_connection_doctor" || name === "get_private_lesson_policy" || name === "inspect_private_lesson_outbox" || name === "inspect_private_learning_outbox" || name === "get_pending_action_payload";
29056
30022
  const openWorld = name === "submit_feedback" || name === "submit_remembrance" || name === "propose_skill_idea" || name === "submit_suggestion" || name === "submit_resource" || name === "submit_resource_review";
29057
30023
  return {
29058
30024
  readOnlyHint: readOnly,
29059
30025
  openWorldHint: openWorld,
29060
30026
  destructiveHint: name === "delete_private_lesson_candidate" || name === "delete_private_skill_candidate",
29061
- ...readOnly || name === "queue_private_skill_import" || name === "acknowledge_feedback_denial" || name === "decline_pending_action" || name === "submit_private_lesson_candidate" || name === "retry_private_lesson_candidate" || name === "submit_private_skill_candidate" || name === "retry_private_skill_candidate" ? { idempotentHint: true } : {}
30027
+ ...readOnly || name === "queue_private_skill_import" || name === "acknowledge_feedback_denial" || name === "decline_pending_action" || name === "submit_private_lesson_candidate" || name === "retry_private_lesson_candidate" || name === "submit_private_skill_candidate" || name === "retry_private_skill_candidate" || name === "repair_review_draft" ? { idempotentHint: true } : {}
29062
30028
  };
29063
30029
  }
29064
30030
  var ROUTINE_PRIVATE_CAPTURE_REPLACED_TOOLS = /* @__PURE__ */ new Set([
@@ -29163,14 +30129,26 @@ function normalizeBoundedWriteJsonSchema(schema, name) {
29163
30129
  schema.allOf = [
29164
30130
  {
29165
30131
  if: { required: ["replacement_of"] },
29166
- then: { required: ["private_skill"] }
30132
+ then: {
30133
+ anyOf: [
30134
+ ["^psd_", "private_skill"],
30135
+ ["^pld_", "lesson"]
30136
+ ].map(([pattern, payload]) => ({
30137
+ required: [payload],
30138
+ properties: {
30139
+ replacement_of: { properties: { draft_id: { pattern } } }
30140
+ }
30141
+ }))
30142
+ }
29167
30143
  }
29168
30144
  ];
29169
30145
  const replacement = schemaProperty(schema, "replacement_of");
29170
- replacement.description = "Optional lineage for a complete replacement of one retained private-skill draft. It carries audit/context identity only and grants no approval, destination authority, or permission to reuse held content.";
29171
- schemaProperty(replacement, "draft_id").description = "Retained encrypted private-skill draft being replaced.";
29172
- schemaProperty(replacement, "context_source").description = "Audit-only source label: active_task_context or separately inspected, explicitly partial safe_recovery_context. Neither source is submission authority.";
29173
- schemaProperty(replacement, "recovery_context_id").description = "Omit this field unless the current inspect_private_learning_outbox agent_recovery.arguments.replacement_of supplies this exact ID. Never invent an ID or derive one from a draft, digest, or ordinary recovery_context. A supplied native context ID may establish a new context epoch but grants no approval or authority to reuse held content. safe_recovery_context alone does not require an ID.";
30146
+ replacement.description = "Optional lineage for a replacement of one retained draft: a complete private skill for a private-skill draft, or a lesson for a held private-lesson draft. It carries audit/context identity only and grants no approval, destination authority, or permission to reuse held content.";
30147
+ const [skillLink, lessonLink] = replacement.anyOf;
30148
+ schemaProperty(skillLink, "draft_id").description = "Retained encrypted private-skill draft being replaced.";
30149
+ schemaProperty(skillLink, "context_source").description = "Audit-only source label: active_task_context or separately inspected, explicitly partial safe_recovery_context. Neither source is submission authority.";
30150
+ schemaProperty(skillLink, "recovery_context_id").description = "Omit this field unless the current inspect_private_learning_outbox agent_recovery.arguments.replacement_of supplies this exact ID. Never invent an ID or derive one from a draft, digest, or ordinary recovery_context. A supplied native context ID may establish a new context epoch but grants no approval or authority to reuse held content. safe_recovery_context alone does not require an ID.";
30151
+ schemaProperty(lessonLink, "draft_id").description = "Held private-lesson draft that this lesson replaces, from its agent_recovery. Write the lesson from the current task, without what the findings name; the held content is never available. The held draft is retired only once the organization accepts this lesson, and accepts at most three versions; a held version is refused with its findings.";
29174
30152
  }
29175
30153
  if (name === "register_agent_key") {
29176
30154
  const metadata = schemaProperty(schema, "metadata");
@@ -30602,6 +31580,7 @@ var PRIVATE_LESSON_CAPACITY_STATE_MAX_BYTES = 1024;
30602
31580
  var PRIVATE_LESSON_OUTBOX_LOCK_NAMESPACE = "outbox";
30603
31581
  var PRIVATE_LESSON_MAX_PAGE_OFFSET = Number.MAX_SAFE_INTEGER - 200;
30604
31582
  var PRIVATE_LESSON_UNVERIFIABLE_COMPLETION_REMEDIATION = "This retained draft records a submission whose completion metadata is missing or invalid, so its acceptance cannot be verified locally. It is kept unchanged and is never resubmitted or retried automatically. Keep it until the user confirms whether the organization received it; delete it with delete_private_lesson_candidate only after explicit confirmation.";
31583
+ var PRIVATE_LESSON_ATTESTATION_MISMATCH_REMEDIATION = "The configured key belongs to a different organization than the owner attested for this recovered draft, and nothing was sent. Only a new owner-attested recovery naming the right destination releases it. Otherwise keep it, or delete it with delete_private_lesson_candidate and confirm=true once the user explicitly confirms.";
30605
31584
  var PrivateLessonPolicyFloorError = class extends Error {
30606
31585
  constructor(message, code) {
30607
31586
  super(message);
@@ -30611,16 +31590,18 @@ var PrivateLessonPolicyFloorError = class extends Error {
30611
31590
  code;
30612
31591
  };
30613
31592
  var PrivateLessonDraftUnavailableError = class extends Error {
30614
- constructor(draftId, reason) {
31593
+ constructor(draftId, reason, replacementDraftId) {
30615
31594
  super(
30616
- reason === "deleted" ? "Private lesson draft was explicitly deleted." : reason === "corrupt" ? "Private lesson draft is retained but its canonical entry is unavailable. Inspect content-free recovery state before taking any destructive action." : "Private lesson draft does not exist. Inspect content-free outbox state before deciding whether task context supports a fresh capture; do not claim that the missing draft was submitted."
31595
+ reason === "deleted" ? "Private lesson draft was explicitly deleted." : reason === "corrupt" ? "Private lesson draft is retained but its canonical entry is unavailable. Inspect content-free recovery state before taking any destructive action." : reason === "replaced" ? "Private lesson draft was held and has been replaced by a re-captured draft the organization accepted; the held draft was never sent and is no longer retained." : "Private lesson draft does not exist. Inspect content-free outbox state before deciding whether task context supports a fresh capture; do not claim that the missing draft was submitted."
30617
31596
  );
30618
31597
  this.draftId = draftId;
30619
31598
  this.reason = reason;
31599
+ this.replacementDraftId = replacementDraftId;
30620
31600
  this.name = "PrivateLessonDraftUnavailableError";
30621
31601
  }
30622
31602
  draftId;
30623
31603
  reason;
31604
+ replacementDraftId;
30624
31605
  jsonRpcCode() {
30625
31606
  return this.reason === "corrupt" ? -32603 : -32602;
30626
31607
  }
@@ -30628,22 +31609,84 @@ var PrivateLessonDraftUnavailableError = class extends Error {
30628
31609
  return {
30629
31610
  code: `private_lesson_draft_${this.reason}`,
30630
31611
  draft_id: this.draftId,
31612
+ ...this.reason === "replaced" && this.replacementDraftId ? { replacement_draft_id: this.replacementDraftId } : {},
30631
31613
  retained_locally: this.reason === "corrupt",
30632
31614
  candidate_sent: false,
30633
31615
  next_action: {
30634
31616
  tool: "inspect_private_lesson_outbox",
30635
- arguments: { draft_id: this.draftId }
31617
+ arguments: {
31618
+ draft_id: this.reason === "replaced" && this.replacementDraftId ? this.replacementDraftId : this.draftId
31619
+ }
30636
31620
  }
30637
31621
  };
30638
31622
  }
30639
31623
  };
31624
+ function privateLessonSafetyRecheck(draft) {
31625
+ return draft.state === "held_safety" && draft.redaction_version === PRIVATE_LESSON_REDACTION_VERSION && draft.redactor_digest !== privateLessonRedactorDigest() && draft.held_reasons.length > 0 && (draft.replacement_attempts ?? []).length === 0 && privateLessonCurrentHoldReasons(draft.candidate, draft.held_reasons).length === 0 ? "passes_current_rule" : null;
31626
+ }
31627
+ var PrivateLessonHoldReleaseRefusedError = class extends Error {
31628
+ constructor(draftId, holdReasons) {
31629
+ super(
31630
+ "The current local safety check still holds this private lesson draft; nothing was sent."
31631
+ );
31632
+ this.draftId = draftId;
31633
+ this.holdReasons = holdReasons;
31634
+ this.name = "PrivateLessonHoldReleaseRefusedError";
31635
+ }
31636
+ draftId;
31637
+ holdReasons;
31638
+ };
31639
+ async function releaseRecheckedPrivateLessonHold(draftId, options = {}) {
31640
+ const outbox = await readyOutbox(options);
31641
+ return withPrivateLessonOutboxLock(outbox.directory, async () => {
31642
+ const draft = await readPrivateLessonDraft(draftId, {
31643
+ ...options,
31644
+ outboxDirectory: outbox.directory,
31645
+ encryption: outbox.encryption
31646
+ });
31647
+ if (draft.state !== "held_safety") return draft;
31648
+ if (!privateLessonSafetyRecheck(draft)) {
31649
+ throw new PrivateLessonHoldReleaseRefusedError(
31650
+ draftId,
31651
+ privateLessonCurrentHoldReasons(draft.candidate, draft.held_reasons)
31652
+ );
31653
+ }
31654
+ const now = (options.now ?? /* @__PURE__ */ new Date()).toISOString();
31655
+ const released = validateDraft({
31656
+ ...draft,
31657
+ state: "retry_scheduled",
31658
+ redactor_digest: privateLessonRedactorDigest(),
31659
+ held_reasons: [],
31660
+ // A policy binding is valid only for its own redactor profile.
31661
+ policy: null,
31662
+ next_retry_at: now,
31663
+ last_error_code: null,
31664
+ hold_telemetry_status: "not_required",
31665
+ hold_event_digest: null,
31666
+ hold_receipt_digest: null,
31667
+ hold_reported_at: null,
31668
+ updated_at: now
31669
+ });
31670
+ await writeDraftUnlocked(released, outbox, true);
31671
+ return released;
31672
+ });
31673
+ }
30640
31674
  async function queuePreparedPrivateLesson(prepared, policy, options = {}) {
30641
- const now = options.now ?? /* @__PURE__ */ new Date();
30642
31675
  const outbox = await readyOutbox(options);
30643
- const draftId = createPublicId("pld");
31676
+ const draft = newPrivateLessonDraft(
31677
+ prepared,
31678
+ createPublicId("pld"),
31679
+ policy,
31680
+ options.destination ?? null,
31681
+ options.now ?? /* @__PURE__ */ new Date()
31682
+ );
31683
+ await writeDraft(draft, outbox, false);
31684
+ return draft;
31685
+ }
31686
+ function newPrivateLessonDraft(prepared, draftId, policy, destination, now) {
30644
31687
  const createdAt = now.toISOString();
30645
31688
  const state = prepared.status === "held_safety" ? "held_safety" : policy ? "ready" : "awaiting_authorization";
30646
- const draft = {
31689
+ return {
30647
31690
  version: PRIVATE_LESSON_OUTBOX_VERSION,
30648
31691
  draft_id: draftId,
30649
31692
  state,
@@ -30654,7 +31697,7 @@ async function queuePreparedPrivateLesson(prepared, policy, options = {}) {
30654
31697
  redactor_digest: prepared.redactor_digest,
30655
31698
  held_reasons: prepared.held_reasons,
30656
31699
  policy,
30657
- destination_binding: options.destination ? parsePrivateLessonDestination(options.destination) : null,
31700
+ destination_binding: destination ? parsePrivateLessonDestination(destination) : null,
30658
31701
  idempotency_key: `private-lesson-${hashValue(
30659
31702
  canonicalJson({
30660
31703
  draft_id: draftId,
@@ -30674,8 +31717,196 @@ async function queuePreparedPrivateLesson(prepared, policy, options = {}) {
30674
31717
  hold_receipt_digest: null,
30675
31718
  hold_reported_at: null
30676
31719
  };
30677
- await writeDraft(draft, outbox, false);
30678
- return draft;
31720
+ }
31721
+ var PRIVATE_LESSON_REPLACEMENT_MAX_ATTEMPTS = 3;
31722
+ var PRIVATE_LESSON_REPLACEMENT_REFUSALS = {
31723
+ unknown: "No retained private lesson draft has this draft_id, so nothing can be replaced. Capture the lesson without replacement_of.",
31724
+ deleted: "This private lesson draft was deleted, so nothing can be replaced. Capture the lesson without replacement_of.",
31725
+ submitted: "This private lesson draft was already sent, so a replacement would be a second lesson. Capture without replacement_of only for a new lesson.",
31726
+ replaced: "This held private lesson draft was already replaced.",
31727
+ not_held: "Only a draft the local safety check holds can be replaced, and this one is not held. Follow its own next_action instead.",
31728
+ destination_changed: "This held private lesson draft was captured for another API base or organization credential than this session uses, and a version written here must not go there. Capture the lesson without replacement_of; the held draft stays as it is.",
31729
+ releasable: "The current safety check would send this held draft as it is, so it is not replaced: the user chooses whether to deliver, keep or delete it.",
31730
+ replacement_pending: "A replacement of this held draft is already retained. Submit it with its next_action, or delete it with delete_private_lesson_candidate and confirm=true before capturing another.",
31731
+ attempts_exhausted: `This held private lesson draft has used all ${PRIVATE_LESSON_REPLACEMENT_MAX_ATTEMPTS} replacement attempts. Keep it, or delete it with delete_private_lesson_candidate and confirm=true once the user confirms.`,
31732
+ replacement_deleted: "This exact replacement was deleted. Capture a different version, or keep or delete the held draft.",
31733
+ replacement_held: "The local safety check holds this replacement too, so it was not stored. Write a version without what the findings name."
31734
+ };
31735
+ var PrivateLessonReplacementRefusedError = class extends Error {
31736
+ constructor(draftId, reason, attemptsRemaining, replacementDraftId) {
31737
+ super(
31738
+ `${PRIVATE_LESSON_REPLACEMENT_REFUSALS[reason]} Nothing was stored or sent.`
31739
+ );
31740
+ this.draftId = draftId;
31741
+ this.reason = reason;
31742
+ this.attemptsRemaining = attemptsRemaining;
31743
+ this.replacementDraftId = replacementDraftId;
31744
+ this.name = "PrivateLessonReplacementRefusedError";
31745
+ }
31746
+ draftId;
31747
+ reason;
31748
+ attemptsRemaining;
31749
+ replacementDraftId;
31750
+ diagnostic() {
31751
+ return {
31752
+ code: "private_lesson_replacement_refused",
31753
+ reason_code: this.reason,
31754
+ replacement_of: this.draftId,
31755
+ ...this.replacementDraftId ? { replacement_draft_id: this.replacementDraftId } : {},
31756
+ attempts_remaining: this.attemptsRemaining,
31757
+ candidate_stored: false,
31758
+ candidate_sent: false
31759
+ };
31760
+ }
31761
+ };
31762
+ async function queuePrivateLessonReplacement(replacementOf, prepared, options = {}) {
31763
+ assertDraftId(replacementOf);
31764
+ const outbox = await readyOutbox(options);
31765
+ const directory = outbox.directory;
31766
+ return withPrivateLessonOutboxLock(directory, async () => {
31767
+ const now = options.now ?? /* @__PURE__ */ new Date();
31768
+ const read2 = { ...options, outboxDirectory: directory };
31769
+ const refuse = (reason, used2 = 0, replacementDraftId) => new PrivateLessonReplacementRefusedError(
31770
+ replacementOf,
31771
+ reason,
31772
+ Math.max(0, PRIVATE_LESSON_REPLACEMENT_MAX_ATTEMPTS - used2),
31773
+ replacementDraftId
31774
+ );
31775
+ await reconcileSubmittedRecordsUnlocked(directory, now);
31776
+ if (existsSync2(tombstonePath(directory, replacementOf))) {
31777
+ throw refuse("deleted");
31778
+ }
31779
+ let original;
31780
+ try {
31781
+ original = await readPrivateLessonDraft(replacementOf, {
31782
+ ...read2,
31783
+ encryption: outbox.encryption
31784
+ });
31785
+ } catch (error) {
31786
+ if (error instanceof PrivateLessonDraftUnavailableError) {
31787
+ if (error.reason === "replaced") {
31788
+ throw refuse(
31789
+ "replaced",
31790
+ PRIVATE_LESSON_REPLACEMENT_MAX_ATTEMPTS,
31791
+ error.replacementDraftId
31792
+ );
31793
+ }
31794
+ if (error.reason === "unknown") throw refuse("unknown");
31795
+ }
31796
+ if (existsSync2(submittedRecordPath(directory, replacementOf))) {
31797
+ throw refuse("submitted");
31798
+ }
31799
+ throw error;
31800
+ }
31801
+ if (original.state === "submitted") throw refuse("submitted");
31802
+ if (original.held_reasons.length === 0 || original.state === "superseded_redactor" || original.replacement_of !== void 0) {
31803
+ throw refuse("not_held");
31804
+ }
31805
+ if (privateLessonSafetyRecheck(original)) throw refuse("releasable");
31806
+ const attempts = original.replacement_attempts ?? [];
31807
+ const digest2 = prepared.payload_digest;
31808
+ const draftId = privateLessonReplacementDraftId(replacementOf, digest2);
31809
+ const replay = attempts.includes(digest2);
31810
+ const used = replay ? attempts.length : attempts.length + 1;
31811
+ if (!replay && privateLessonCapturedForOtherDestination(original, options.destination)) {
31812
+ throw refuse("destination_changed", attempts.length);
31813
+ }
31814
+ const pending = attempts.map((attempt) => privateLessonReplacementDraftId(replacementOf, attempt)).find(
31815
+ (candidate) => candidate !== draftId && existsSync2(draftPath(directory, candidate))
31816
+ );
31817
+ if (pending) throw refuse("replacement_pending", attempts.length, pending);
31818
+ if (!replay) {
31819
+ if (attempts.length >= PRIVATE_LESSON_REPLACEMENT_MAX_ATTEMPTS) {
31820
+ throw refuse("attempts_exhausted", attempts.length);
31821
+ }
31822
+ await writeDraftUnlocked(
31823
+ validateDraft({
31824
+ ...original,
31825
+ replacement_attempts: [...attempts, digest2],
31826
+ updated_at: now.toISOString()
31827
+ }),
31828
+ outbox,
31829
+ true
31830
+ );
31831
+ }
31832
+ if (prepared.status === "held_safety") {
31833
+ throw refuse("replacement_held", used);
31834
+ }
31835
+ if (existsSync2(tombstonePath(directory, draftId))) {
31836
+ throw refuse("replacement_deleted", used, draftId);
31837
+ }
31838
+ if (existsSync2(draftPath(directory, draftId))) {
31839
+ return {
31840
+ draft: await readPrivateLessonDraft(draftId, {
31841
+ ...read2,
31842
+ encryption: outbox.encryption
31843
+ }),
31844
+ attempts_remaining: PRIVATE_LESSON_REPLACEMENT_MAX_ATTEMPTS - used,
31845
+ replayed: true
31846
+ };
31847
+ }
31848
+ const draft = {
31849
+ ...newPrivateLessonDraft(
31850
+ prepared,
31851
+ draftId,
31852
+ null,
31853
+ original.destination_binding ?? options.destination ?? null,
31854
+ now
31855
+ ),
31856
+ ...original.attested_organization_audience_hash !== void 0 ? {
31857
+ attested_organization_audience_hash: original.attested_organization_audience_hash
31858
+ } : {},
31859
+ replacement_of: replacementOf
31860
+ };
31861
+ await writeDraftUnlocked(validateDraft(draft), outbox, false);
31862
+ return {
31863
+ draft,
31864
+ attempts_remaining: PRIVATE_LESSON_REPLACEMENT_MAX_ATTEMPTS - used,
31865
+ replayed: replay
31866
+ };
31867
+ });
31868
+ }
31869
+ async function retireReplacedPrivateLessonUnlocked(directory, draftId, replacementDraftId, at) {
31870
+ const path = draftPath(directory, draftId);
31871
+ if (existsSync2(tombstonePath(directory, draftId)) || existsSync2(submittedRecordPath(directory, draftId)) || !existsSync2(path)) {
31872
+ return;
31873
+ }
31874
+ try {
31875
+ await assertRegularPrivateFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES);
31876
+ const envelope = parseEnvelope(
31877
+ await readBoundedFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES),
31878
+ draftId
31879
+ );
31880
+ if (envelope.state === "submitted") return;
31881
+ } catch {
31882
+ return;
31883
+ }
31884
+ const record4 = {
31885
+ version: "private-lesson-outbox-deletion-v1",
31886
+ draft_id: draftId,
31887
+ deleted_at: at.toISOString(),
31888
+ reason: "replaced_by_verified_replacement",
31889
+ replacement_draft_id: replacementDraftId,
31890
+ expires_at: new Date(
31891
+ at.getTime() + PRIVATE_LESSON_SUBMITTED_RECORD_RETENTION_MS
31892
+ ).toISOString()
31893
+ };
31894
+ await atomicCreatePrivateLessonEntry(
31895
+ replacedRecordPath(directory, draftId),
31896
+ `${JSON.stringify(record4)}
31897
+ `,
31898
+ ".replaced.tmp"
31899
+ );
31900
+ await unlink2(path).catch(() => {
31901
+ });
31902
+ await syncDirectory2(directory).catch(() => {
31903
+ });
31904
+ }
31905
+ function acceptedPrivateLessonReplacement(directory, draft) {
31906
+ if (draft.state === "submitted") return void 0;
31907
+ return (draft.replacement_attempts ?? []).map((digest2) => privateLessonReplacementDraftId(draft.draft_id, digest2)).find(
31908
+ (replacement) => existsSync2(submittedRecordPath(directory, replacement))
31909
+ );
30679
31910
  }
30680
31911
  async function readPrivateLessonDraft(draftId, options = {}) {
30681
31912
  assertDraftId(draftId);
@@ -30688,10 +31919,12 @@ async function readPrivateLessonDraft(draftId, options = {}) {
30688
31919
  if (existsSync2(tombstonePath(outbox.directory, draftId))) {
30689
31920
  throw new PrivateLessonDraftUnavailableError(draftId, "deleted");
30690
31921
  }
31922
+ await assertNotReplacedUnlocked(outbox.directory, draftId);
30691
31923
  if (existsSync2(submittedRecordPath(outbox.directory, draftId))) {
30692
31924
  throw new Error("Private lesson draft was already submitted.");
30693
31925
  }
30694
31926
  let draft;
31927
+ let envelope;
30695
31928
  try {
30696
31929
  const path = draftPath(outbox.directory, draftId);
30697
31930
  await assertRegularPrivateFile(path, PRIVATE_LESSON_DRAFT_MAX_BYTES);
@@ -30699,20 +31932,32 @@ async function readPrivateLessonDraft(draftId, options = {}) {
30699
31932
  path,
30700
31933
  PRIVATE_LESSON_DRAFT_MAX_BYTES
30701
31934
  );
30702
- const envelope = parseEnvelope(serialized, draftId);
31935
+ envelope = parseEnvelope(serialized, draftId);
30703
31936
  draft = await decryptDraft(envelope, outbox.encryption, true);
30704
31937
  } catch (error) {
30705
31938
  throw selectedPrivateLessonError(draftId, error);
30706
31939
  }
30707
- const profileReconciled = terminalizeUnsupportedProfile(
30708
- draft,
30709
- options.now ?? /* @__PURE__ */ new Date()
30710
- );
30711
- const reconciled = normalizeLegacyHeldSafetyDraft(
30712
- profileReconciled,
30713
- options.now ?? /* @__PURE__ */ new Date()
31940
+ const now = options.now ?? /* @__PURE__ */ new Date();
31941
+ const replacement = acceptedPrivateLessonReplacement(
31942
+ outbox.directory,
31943
+ draft
30714
31944
  );
30715
- if (reconciled !== draft) {
31945
+ if (replacement) {
31946
+ await retireReplacedPrivateLessonUnlocked(
31947
+ outbox.directory,
31948
+ draftId,
31949
+ replacement,
31950
+ now
31951
+ ).catch(() => {
31952
+ });
31953
+ throw new PrivateLessonDraftUnavailableError(
31954
+ draftId,
31955
+ "replaced",
31956
+ replacement
31957
+ );
31958
+ }
31959
+ const reconciled = reconcileStoredDraft(draft, now);
31960
+ if (reconciled !== draft || staleSafetyRecheckHint(envelope, reconciled)) {
30716
31961
  await writeDraft(reconciled, outbox, true, void 0, true);
30717
31962
  }
30718
31963
  return reconciled;
@@ -30731,6 +31976,7 @@ async function readPrivateLessonSubmittedRecord(draftId, options = {}) {
30731
31976
  if (existsSync2(tombstonePath(directory, draftId))) {
30732
31977
  throw new PrivateLessonDraftUnavailableError(draftId, "deleted");
30733
31978
  }
31979
+ await assertNotReplacedUnlocked(directory, draftId);
30734
31980
  const path = submittedRecordPath(directory, draftId);
30735
31981
  if (!existsSync2(path)) return null;
30736
31982
  await assertRegularPrivateFile(
@@ -30754,6 +32000,7 @@ async function readPrivateLessonSubmissionSource(draftId, options = {}) {
30754
32000
  if (existsSync2(tombstonePath(outbox.directory, draftId))) {
30755
32001
  throw new PrivateLessonDraftUnavailableError(draftId, "deleted");
30756
32002
  }
32003
+ await assertNotReplacedUnlocked(outbox.directory, draftId);
30757
32004
  const completionPath = submittedRecordPath(outbox.directory, draftId);
30758
32005
  if (existsSync2(completionPath)) {
30759
32006
  await assertRegularPrivateFile(
@@ -30786,7 +32033,7 @@ async function readPrivateLessonSubmissionSource(draftId, options = {}) {
30786
32033
  return { kind: "draft", draft };
30787
32034
  });
30788
32035
  }
30789
- async function reconcilePrivateLessonOutboxProfiles(options = {}) {
32036
+ async function reconcilePrivateLessonOutboxProfiles(options = {}, replaced) {
30790
32037
  const outbox = await readyOutbox(options, false);
30791
32038
  return withPrivateLessonOutboxLock(outbox.directory, async () => {
30792
32039
  await reconcilePrivateLessonTemporaryWrites(
@@ -30820,7 +32067,10 @@ async function reconcilePrivateLessonOutboxProfiles(options = {}) {
30820
32067
  outboxDirectory: outbox.directory,
30821
32068
  encryption: outbox.encryption
30822
32069
  });
30823
- } catch {
32070
+ } catch (error) {
32071
+ if (error instanceof PrivateLessonDraftUnavailableError && error.reason === "replaced") {
32072
+ replaced?.add(draftId);
32073
+ }
30824
32074
  continue;
30825
32075
  }
30826
32076
  inspected += 1;
@@ -30853,7 +32103,7 @@ async function updatePrivateLessonDraft(draftId, update, options = {}) {
30853
32103
  throw new PrivateLessonDraftUnavailableError(draftId, "corrupt");
30854
32104
  }
30855
32105
  const next = validateDraft(update(structuredClone(current)));
30856
- if (next.draft_id !== current.draft_id || next.payload_digest !== current.payload_digest || next.canonical_payload !== current.canonical_payload || next.redaction_version !== current.redaction_version || next.redactor_digest !== current.redactor_digest || canonicalJson(next.destination_binding) !== canonicalJson(current.destination_binding) || next.idempotency_key !== current.idempotency_key) {
32106
+ if (next.draft_id !== current.draft_id || next.payload_digest !== current.payload_digest || next.canonical_payload !== current.canonical_payload || next.redaction_version !== current.redaction_version || next.redactor_digest !== current.redactor_digest || canonicalJson(next.destination_binding) !== canonicalJson(current.destination_binding) || next.attested_organization_audience_hash !== current.attested_organization_audience_hash || next.idempotency_key !== current.idempotency_key) {
30857
32107
  throw new Error("Private lesson draft content is immutable.");
30858
32108
  }
30859
32109
  next.updated_at = (options.now ?? /* @__PURE__ */ new Date()).toISOString();
@@ -30872,6 +32122,7 @@ async function completePrivateLessonSubmission(draftId, input, options = {}) {
30872
32122
  if (existsSync2(tombstonePath(outbox.directory, draftId))) {
30873
32123
  throw new PrivateLessonDraftUnavailableError(draftId, "deleted");
30874
32124
  }
32125
+ await assertNotReplacedUnlocked(outbox.directory, draftId);
30875
32126
  const existingPath = submittedRecordPath(outbox.directory, draftId);
30876
32127
  if (existsSync2(existingPath)) {
30877
32128
  let completion2;
@@ -30903,6 +32154,7 @@ async function completePrivateLessonSubmission(draftId, input, options = {}) {
30903
32154
  } catch (error) {
30904
32155
  throw selectedPrivateLessonError(draftId, error);
30905
32156
  }
32157
+ current = reconcileStoredDraft(current, options.now ?? /* @__PURE__ */ new Date());
30906
32158
  if (current.state === "superseded_redactor") {
30907
32159
  throw new Error("Terminal private lesson drafts cannot be submitted.");
30908
32160
  }
@@ -30934,6 +32186,15 @@ async function completePrivateLessonSubmission(draftId, input, options = {}) {
30934
32186
  });
30935
32187
  await syncDirectory2(outbox.directory).catch(() => {
30936
32188
  });
32189
+ if (draft.replacement_of) {
32190
+ await retireReplacedPrivateLessonUnlocked(
32191
+ outbox.directory,
32192
+ draft.replacement_of,
32193
+ draftId,
32194
+ submittedAt
32195
+ ).catch(() => {
32196
+ });
32197
+ }
30937
32198
  return completion;
30938
32199
  });
30939
32200
  }
@@ -30949,19 +32210,21 @@ async function deletePrivateLessonDraft(draftId, confirmed, options = {}) {
30949
32210
  const path = draftPath(outbox.directory, draftId);
30950
32211
  const completionPath = submittedRecordPath(outbox.directory, draftId);
30951
32212
  const deletionPath = tombstonePath(outbox.directory, draftId);
32213
+ const replacedPath = replacedRecordPath(outbox.directory, draftId);
30952
32214
  const quarantined = await privateLessonQuarantineEntriesForDraft(
30953
32215
  outbox.directory,
30954
32216
  draftId
30955
32217
  );
30956
- if (existsSync2(deletionPath) && !existsSync2(path) && !existsSync2(completionPath) && quarantined.length === 0) {
32218
+ if (existsSync2(deletionPath) && !existsSync2(path) && !existsSync2(completionPath) && !existsSync2(replacedPath) && quarantined.length === 0) {
30957
32219
  throw new PrivateLessonDraftUnavailableError(draftId, "deleted");
30958
32220
  }
30959
- if (!existsSync2(path) && !existsSync2(completionPath) && !existsSync2(deletionPath) && quarantined.length === 0) {
32221
+ if (!existsSync2(path) && !existsSync2(completionPath) && !existsSync2(deletionPath) && !existsSync2(replacedPath) && quarantined.length === 0) {
30960
32222
  throw new PrivateLessonDraftUnavailableError(draftId, "unknown");
30961
32223
  }
30962
32224
  await removeCanonicalPrivateLessonEntry(path);
30963
32225
  await removeCanonicalPrivateLessonEntry(completionPath);
30964
32226
  await removeCanonicalPrivateLessonEntry(deletionPath);
32227
+ await removeCanonicalPrivateLessonEntry(replacedPath);
30965
32228
  for (const entry of quarantined) {
30966
32229
  await removeCanonicalPrivateLessonEntry(entry);
30967
32230
  }
@@ -30982,11 +32245,15 @@ async function deletePrivateLessonDraft(draftId, confirmed, options = {}) {
30982
32245
  }
30983
32246
  async function privateLessonOutboxSummary(options = {}) {
30984
32247
  const outbox = await readyOutbox(options, false);
30985
- await reconcilePrivateLessonOutboxProfiles({
30986
- ...options,
30987
- outboxDirectory: outbox.directory,
30988
- encryption: outbox.encryption
30989
- });
32248
+ const replaced = /* @__PURE__ */ new Set();
32249
+ await reconcilePrivateLessonOutboxProfiles(
32250
+ {
32251
+ ...options,
32252
+ outboxDirectory: outbox.directory,
32253
+ encryption: outbox.encryption
32254
+ },
32255
+ replaced
32256
+ );
30990
32257
  const entries = await secureOutboxEntries(outbox.directory);
30991
32258
  const counts = {
30992
32259
  ready: 0,
@@ -31001,6 +32268,7 @@ async function privateLessonOutboxSummary(options = {}) {
31001
32268
  };
31002
32269
  let totalBytes = 0;
31003
32270
  let deletionTombstones = 0;
32271
+ let replacedRecords = 0;
31004
32272
  let terminalBytes = 0;
31005
32273
  const terminalReasons = {};
31006
32274
  let corruptFiles = 0;
@@ -31011,6 +32279,10 @@ async function privateLessonOutboxSummary(options = {}) {
31011
32279
  deletionTombstones += 1;
31012
32280
  continue;
31013
32281
  }
32282
+ if (name.endsWith(".replaced.json")) {
32283
+ replacedRecords += 1;
32284
+ continue;
32285
+ }
31014
32286
  if (name.endsWith(".submitted.json")) {
31015
32287
  const draftId = name.slice(0, -".submitted.json".length);
31016
32288
  try {
@@ -31028,6 +32300,10 @@ async function privateLessonOutboxSummary(options = {}) {
31028
32300
  continue;
31029
32301
  }
31030
32302
  if (!name.endsWith(".lesson.json")) continue;
32303
+ if (replaced.has(name.slice(0, -".lesson.json".length))) {
32304
+ replacedRecords += 1;
32305
+ continue;
32306
+ }
31031
32307
  let envelope;
31032
32308
  try {
31033
32309
  envelope = parseEnvelope(
@@ -31084,6 +32360,7 @@ async function privateLessonOutboxSummary(options = {}) {
31084
32360
  terminal_reasons: terminalReasons,
31085
32361
  deletion_guidance: counts.superseded_redactor > 0 ? "Update the client, then re-capture the lesson with capture_learning before considering deletion. Delete the superseded draft with delete_private_lesson_candidate only after confirming the replacement was retained or accepted." : null,
31086
32362
  deletion_tombstones: deletionTombstones,
32363
+ replaced_records: replacedRecords,
31087
32364
  temporary_files: retainedArtifacts.temporaryFiles,
31088
32365
  corrupt_files: Math.max(
31089
32366
  corruptFiles,
@@ -31113,13 +32390,14 @@ async function inspectPrivateLessonOutboxSnapshotUnlocked(outbox, options) {
31113
32390
  const recoveryItems = [];
31114
32391
  const terminalReasons = {};
31115
32392
  let deletionTombstones = 0;
32393
+ let replacedRecords = 0;
31116
32394
  let terminalBytes = 0;
31117
32395
  let corruptFiles = 0;
31118
32396
  for (const entry of await readdir(outbox.directory, {
31119
32397
  withFileTypes: true
31120
32398
  })) {
31121
32399
  const match = entry.name.match(
31122
- /^(pld_[A-Za-z0-9_-]{8,96})\.(lesson|submitted|deleted)\.json$/u
32400
+ /^(pld_[A-Za-z0-9_-]{8,96})\.(lesson|submitted|deleted|replaced)\.json$/u
31123
32401
  );
31124
32402
  if (!match) continue;
31125
32403
  const draftId = match[1];
@@ -31131,6 +32409,25 @@ async function inspectPrivateLessonOutboxSnapshotUnlocked(outbox, options) {
31131
32409
  continue;
31132
32410
  }
31133
32411
  const path = join3(outbox.directory, entry.name);
32412
+ if (entry.name.endsWith(".replaced.json")) {
32413
+ replacedRecords += 1;
32414
+ try {
32415
+ parseReplacedRecord(
32416
+ await readPrivateLessonCanonicalText(
32417
+ path,
32418
+ PRIVATE_LESSON_SUBMITTED_RECORD_MAX_BYTES
32419
+ ),
32420
+ draftId
32421
+ );
32422
+ } catch (error) {
32423
+ if (error instanceof PrivateOutboxStorageError) throw error;
32424
+ recoveryItems.push(
32425
+ privateLessonRecoveryItem(draftId, "invalid_canonical_entry")
32426
+ );
32427
+ corruptFiles += 1;
32428
+ }
32429
+ continue;
32430
+ }
31134
32431
  if (entry.name.endsWith(".deleted.json")) {
31135
32432
  let serialized2;
31136
32433
  deletionTombstones += 1;
@@ -31229,9 +32526,24 @@ async function inspectPrivateLessonOutboxSnapshotUnlocked(outbox, options) {
31229
32526
  corruptFiles += 1;
31230
32527
  continue;
31231
32528
  }
31232
- const profileReconciled = terminalizeUnsupportedProfile(decrypted, now);
31233
- const draft = normalizeLegacyHeldSafetyDraft(profileReconciled, now);
31234
- if (draft !== decrypted) {
32529
+ const replacement = acceptedPrivateLessonReplacement(
32530
+ outbox.directory,
32531
+ decrypted
32532
+ );
32533
+ if (replacement) {
32534
+ counts[envelope.state] -= 1;
32535
+ replacedRecords += 1;
32536
+ await retireReplacedPrivateLessonUnlocked(
32537
+ outbox.directory,
32538
+ draftId,
32539
+ replacement,
32540
+ now
32541
+ ).catch(() => {
32542
+ });
32543
+ continue;
32544
+ }
32545
+ const draft = reconcileStoredDraft(decrypted, now);
32546
+ if (draft !== decrypted || staleSafetyRecheckHint(envelope, draft)) {
31235
32547
  counts[envelope.state] -= 1;
31236
32548
  counts[draft.state] += 1;
31237
32549
  await writeDraftUnlocked(draft, outbox, true, void 0, true);
@@ -31305,6 +32617,7 @@ async function inspectPrivateLessonOutboxSnapshotUnlocked(outbox, options) {
31305
32617
  terminal_reasons: terminalReasons,
31306
32618
  deletion_guidance: counts.superseded_redactor > 0 ? "Update the client, then re-capture the lesson with capture_learning before considering deletion. Delete the superseded draft with delete_private_lesson_candidate only after confirming the replacement was retained or accepted." : null,
31307
32619
  deletion_tombstones: deletionTombstones,
32620
+ replaced_records: replacedRecords,
31308
32621
  temporary_files: retainedArtifacts.temporaryFiles,
31309
32622
  corrupt_files: Math.max(
31310
32623
  corruptFiles,
@@ -31374,6 +32687,7 @@ async function inspectPrivateLessonOutboxHealth(options = {}) {
31374
32687
  terminal_reasons: {},
31375
32688
  deletion_guidance: null,
31376
32689
  deletion_tombstones: 0,
32690
+ replaced_records: 0,
31377
32691
  temporary_files: 0,
31378
32692
  corrupt_files: 0,
31379
32693
  quarantined_bytes: 0,
@@ -31412,6 +32726,7 @@ async function inspectPrivateLessonOutboxHealth(options = {}) {
31412
32726
  const counts = emptyOutboxCounts();
31413
32727
  let totalBytes = 0;
31414
32728
  let deletionTombstones = 0;
32729
+ let replacedRecords = 0;
31415
32730
  let terminalBytes = 0;
31416
32731
  let corruptFiles = 0;
31417
32732
  const terminalReasons = {};
@@ -31423,6 +32738,10 @@ async function inspectPrivateLessonOutboxHealth(options = {}) {
31423
32738
  deletionTombstones += 1;
31424
32739
  continue;
31425
32740
  }
32741
+ if (name.endsWith(".replaced.json")) {
32742
+ replacedRecords += 1;
32743
+ continue;
32744
+ }
31426
32745
  if (name.endsWith(".submitted.json")) {
31427
32746
  const draftId = name.slice(0, -".submitted.json".length);
31428
32747
  try {
@@ -31479,6 +32798,7 @@ async function inspectPrivateLessonOutboxHealth(options = {}) {
31479
32798
  terminal_reasons: terminalReasons,
31480
32799
  deletion_guidance: counts.superseded_redactor > 0 ? "Update the client, then re-capture the lesson with capture_learning before considering deletion. Delete the superseded draft with delete_private_lesson_candidate only after confirming the replacement was retained or accepted." : null,
31481
32800
  deletion_tombstones: deletionTombstones,
32801
+ replaced_records: replacedRecords,
31482
32802
  temporary_files: retainedArtifacts.temporaryFiles,
31483
32803
  corrupt_files: corruptFiles,
31484
32804
  quarantined_bytes: retainedArtifacts.quarantinedBytes,
@@ -31903,6 +33223,7 @@ async function writeDraftUnlocked(draft, outbox, replace, _currentOutboxBytes, a
31903
33223
  created_at: validated.created_at,
31904
33224
  updated_at: validated.updated_at,
31905
33225
  destination_binding: validated.destination_binding,
33226
+ ...safetyRecheckField(validated),
31906
33227
  encryption: {
31907
33228
  algorithm: "aes-256-gcm",
31908
33229
  key_source: outbox.encryption.source,
@@ -31930,7 +33251,7 @@ async function writeDraftUnlocked(draft, outbox, replace, _currentOutboxBytes, a
31930
33251
  if (replace) {
31931
33252
  await atomicReplacePrivate(path, serialized);
31932
33253
  } else {
31933
- await atomicCreatePrivateLessonDraft(path, serialized);
33254
+ await atomicCreatePrivateLessonEntry(path, serialized);
31934
33255
  }
31935
33256
  }
31936
33257
  async function decryptDraft(envelope, encryption, allowUnsupportedProfile = false) {
@@ -32045,19 +33366,37 @@ function validateDraft(value, allowUnsupportedProfile = false) {
32045
33366
  );
32046
33367
  }
32047
33368
  }
33369
+ if (value.attested_organization_audience_hash !== void 0 && !isSha256Digest(value.attested_organization_audience_hash)) {
33370
+ throw new Error("Private lesson draft attested audience is invalid.");
33371
+ }
33372
+ if (value.replacement_of !== void 0 && (typeof value.replacement_of !== "string" || !/^pld_[A-Za-z0-9_-]{8,96}$/u.test(value.replacement_of) || value.replacement_of === value.draft_id)) {
33373
+ throw new Error("Private lesson draft replacement link is invalid.");
33374
+ }
33375
+ if (value.replacement_attempts !== void 0 && (!Array.isArray(value.replacement_attempts) || value.replacement_attempts.length > PRIVATE_LESSON_REPLACEMENT_MAX_ATTEMPTS || !value.replacement_attempts.every(isSha256Digest) || new Set(value.replacement_attempts).size !== value.replacement_attempts.length)) {
33376
+ throw new Error("Private lesson draft replacement attempts are invalid.");
33377
+ }
32048
33378
  const destinationBinding = value.destination_binding === void 0 ? null : value.destination_binding === null ? null : parsePrivateLessonDestination(value.destination_binding);
32049
33379
  return {
32050
33380
  ...value,
32051
33381
  destination_binding: destinationBinding
32052
33382
  };
32053
33383
  }
32054
- function terminalizeUnsupportedProfile(draft, now) {
33384
+ function staleSafetyRecheckHint(envelope, draft) {
33385
+ return (envelope.safety_recheck ?? null) !== privateLessonSafetyRecheck(draft);
33386
+ }
33387
+ function reconcileStoredDraft(draft, now) {
33388
+ return normalizeLegacyHeldSafetyDraft(
33389
+ reconcileRedactorProfile(draft, now),
33390
+ now
33391
+ );
33392
+ }
33393
+ function reconcileRedactorProfile(draft, now) {
32055
33394
  try {
32056
33395
  privateLessonRedactorProfile(
32057
33396
  draft.redaction_version,
32058
33397
  draft.redactor_digest
32059
33398
  );
32060
- return draft;
33399
+ return resumeDraftRetiredByOlderClient(draft, now);
32061
33400
  } catch (error) {
32062
33401
  if (!(error instanceof PrivateLessonRedactionProfileError)) throw error;
32063
33402
  if (draft.state === "superseded_redactor" && draft.terminal_reason === error.code || // Accepted work is not a draft awaiting a current redactor. Keep a
@@ -32076,6 +33415,18 @@ function terminalizeUnsupportedProfile(draft, now) {
32076
33415
  };
32077
33416
  }
32078
33417
  }
33418
+ function resumeDraftRetiredByOlderClient(draft, now) {
33419
+ if (draft.state !== "superseded_redactor") return draft;
33420
+ const held = draft.held_reasons.length > 0;
33421
+ return validateDraft({
33422
+ ...draft,
33423
+ state: held ? "held_safety" : "retry_scheduled",
33424
+ terminal_reason: null,
33425
+ next_retry_at: held ? null : now.toISOString(),
33426
+ hold_telemetry_status: !held ? "not_required" : draft.hold_telemetry_status === "submitted" ? "submitted" : "pending",
33427
+ updated_at: now.toISOString()
33428
+ });
33429
+ }
32079
33430
  function normalizeLegacyHeldSafetyDraft(draft, now) {
32080
33431
  if (draft.state !== "held_safety" || draft.held_reasons.length > 0) {
32081
33432
  return draft;
@@ -32192,6 +33543,9 @@ async function reconcileSubmittedRecordsUnlocked(directory, now) {
32192
33543
  changed = true;
32193
33544
  }
32194
33545
  }
33546
+ if (await reconcileReplacedRecordsUnlocked(directory, entries, now)) {
33547
+ changed = true;
33548
+ }
32195
33549
  if (changed) await syncDirectory2(directory);
32196
33550
  }
32197
33551
  function submittedRecordListItem(completion) {
@@ -32227,9 +33581,64 @@ function privateLessonDraftListItem(draft) {
32227
33581
  terminal_reason: draft.terminal_reason,
32228
33582
  hold_telemetry_status: draft.hold_telemetry_status,
32229
33583
  hold_event_digest: draft.hold_event_digest,
32230
- hold_reported_at: draft.hold_reported_at
33584
+ hold_reported_at: draft.hold_reported_at,
33585
+ ...safetyRecheckField(draft)
32231
33586
  };
32232
33587
  }
33588
+ function safetyRecheckField(draft) {
33589
+ const recheck = privateLessonSafetyRecheck(draft);
33590
+ return recheck ? { safety_recheck: recheck } : {};
33591
+ }
33592
+ function privateLessonReplaceable(draft, destination) {
33593
+ return draft.held_reasons.length > 0 && draft.state !== "submitted" && draft.state !== "superseded_redactor" && draft.replacement_of === void 0 && privateLessonSafetyRecheck(draft) === null && !privateLessonCapturedForOtherDestination(draft, destination);
33594
+ }
33595
+ function privateLessonCapturedForOtherDestination(draft, destination) {
33596
+ const bound = draft.destination_binding;
33597
+ return Boolean(
33598
+ bound && destination && (bound.api_base_sha256 !== destination.api_base_sha256 || bound.credential_sha256 !== destination.credential_sha256)
33599
+ );
33600
+ }
33601
+ function privateLessonReplacementAttemptsRemaining(draft) {
33602
+ return Math.max(
33603
+ 0,
33604
+ PRIVATE_LESSON_REPLACEMENT_MAX_ATTEMPTS - (draft.replacement_attempts ?? []).length
33605
+ );
33606
+ }
33607
+ function privateLessonAgentRecovery(draftId, attemptsRemaining) {
33608
+ if (attemptsRemaining <= 0) return null;
33609
+ return {
33610
+ tool: "capture_learning",
33611
+ action_code: "recapture_held_private_lesson",
33612
+ arguments: {
33613
+ contract_version: PRIVATE_LEARNING_CAPTURE_VERSION,
33614
+ replacement_of: { draft_id: draftId }
33615
+ },
33616
+ required_input: ["lesson"],
33617
+ context_requirement: "existing_task_context",
33618
+ attempts_remaining: attemptsRemaining,
33619
+ retained_original_available_to_agent: false
33620
+ };
33621
+ }
33622
+ function privateLessonRecoveryFields(draft, destination) {
33623
+ if (draft.replacement_of !== void 0) {
33624
+ return { replacement_of: draft.replacement_of };
33625
+ }
33626
+ if (!privateLessonReplaceable(draft)) return {};
33627
+ const remaining = privateLessonReplacementAttemptsRemaining(draft);
33628
+ if (remaining > 0 && !privateLessonReplaceable(draft, destination)) {
33629
+ return {
33630
+ replacement_attempts_remaining: remaining,
33631
+ replacement_requires_captured_destination: true
33632
+ };
33633
+ }
33634
+ return {
33635
+ replacement_attempts_remaining: remaining,
33636
+ agent_recovery: privateLessonAgentRecovery(draft.draft_id, remaining)
33637
+ };
33638
+ }
33639
+ function privateLessonHeldRecoveryActionRequired(attemptsRemaining, capturedDestinationRequired = false) {
33640
+ return attemptsRemaining <= 0 ? "The local safety check holds this lesson draft (held_reasons), so it will not be sent, and it has used every replacement attempt. Keep it, or delete it with delete_private_lesson_candidate and confirm=true once the user confirms." : capturedDestinationRequired ? "The local safety check holds this lesson draft (held_reasons), so it will not be sent. It was captured for another API base or organization credential than this session uses, so a version written here cannot replace it (replacement_requires_captured_destination). Keep it, delete it with delete_private_lesson_candidate and confirm=true, or replace it from a session that uses its own destination. Never resubmit the held content." : "The local safety check holds this lesson draft (held_reasons), so it will not be sent. If this task still has the lesson, write a version without what holds it and capture it as agent_recovery says (capture_learning with replacement_of); this draft is replaced only once that version is accepted. Otherwise keep it, or delete it with delete_private_lesson_candidate and confirm=true. Never resubmit the held content.";
33641
+ }
32233
33642
  function privateLessonPageOffset(value) {
32234
33643
  const requested = Math.trunc(value ?? 0);
32235
33644
  if (!Number.isSafeInteger(requested)) {
@@ -32289,6 +33698,79 @@ function parseDeletionTombstone(serialized, expectedDraftId) {
32289
33698
  }
32290
33699
  return value;
32291
33700
  }
33701
+ function parseReplacedRecord(serialized, expectedDraftId) {
33702
+ const value = JSON.parse(serialized);
33703
+ const allowedKeys = /* @__PURE__ */ new Set([
33704
+ "version",
33705
+ "draft_id",
33706
+ "deleted_at",
33707
+ "reason",
33708
+ "replacement_draft_id",
33709
+ "expires_at"
33710
+ ]);
33711
+ if (!isRecord3(value) || Object.keys(value).some((key) => !allowedKeys.has(key)) || value.version !== "private-lesson-outbox-deletion-v1" || value.draft_id !== expectedDraftId || value.reason !== "replaced_by_verified_replacement" || typeof value.replacement_draft_id !== "string" || !/^pld_[A-Za-z0-9_-]{8,96}$/u.test(value.replacement_draft_id) || value.replacement_draft_id === expectedDraftId || !isIsoTimestamp(value.deleted_at) || !isIsoTimestamp(value.expires_at) || Date.parse(value.expires_at) <= Date.parse(value.deleted_at)) {
33712
+ throw new Error("Private lesson replaced record is invalid.");
33713
+ }
33714
+ return value;
33715
+ }
33716
+ async function readReplacedRecordUnlocked(directory, draftId) {
33717
+ const path = replacedRecordPath(directory, draftId);
33718
+ if (!existsSync2(path)) return null;
33719
+ try {
33720
+ await assertRegularPrivateFile(path, PRIVATE_LESSON_SUBMITTED_RECORD_MAX_BYTES);
33721
+ return parseReplacedRecord(
33722
+ await readBoundedFile(path, PRIVATE_LESSON_SUBMITTED_RECORD_MAX_BYTES),
33723
+ draftId
33724
+ );
33725
+ } catch (error) {
33726
+ if (error instanceof PrivateOutboxStorageError) throw error;
33727
+ throw new PrivateLessonDraftUnavailableError(draftId, "corrupt");
33728
+ }
33729
+ }
33730
+ async function assertNotReplacedUnlocked(directory, draftId) {
33731
+ const replaced = await readReplacedRecordUnlocked(directory, draftId);
33732
+ if (replaced) {
33733
+ throw new PrivateLessonDraftUnavailableError(
33734
+ draftId,
33735
+ "replaced",
33736
+ replaced.replacement_draft_id
33737
+ );
33738
+ }
33739
+ }
33740
+ async function reconcileReplacedRecordsUnlocked(directory, entries, now) {
33741
+ let changed = false;
33742
+ for (const name of entries.filter(
33743
+ (entry) => entry.endsWith(".replaced.json")
33744
+ )) {
33745
+ const draftId = name.slice(0, -".replaced.json".length);
33746
+ let record4;
33747
+ try {
33748
+ record4 = parseReplacedRecord(
33749
+ await readBoundedFile(
33750
+ join3(directory, name),
33751
+ PRIVATE_LESSON_SUBMITTED_RECORD_MAX_BYTES
33752
+ ),
33753
+ draftId
33754
+ );
33755
+ } catch {
33756
+ continue;
33757
+ }
33758
+ const retained = draftPath(directory, draftId);
33759
+ if (existsSync2(retained)) {
33760
+ try {
33761
+ await assertRegularPrivateFile(retained, PRIVATE_LESSON_DRAFT_MAX_BYTES);
33762
+ await unlink2(retained);
33763
+ changed = true;
33764
+ } catch {
33765
+ }
33766
+ }
33767
+ if (Date.parse(record4.expires_at) <= now.getTime()) {
33768
+ await unlink2(join3(directory, name));
33769
+ changed = true;
33770
+ }
33771
+ }
33772
+ return changed;
33773
+ }
32292
33774
  async function privateLessonRecoveryItems(options = {}) {
32293
33775
  const outbox = await readyOutbox(options, false);
32294
33776
  return withPrivateLessonOutboxLock(outbox.directory, async () => {
@@ -32301,7 +33783,7 @@ async function privateLessonRecoveryItems(options = {}) {
32301
33783
  withFileTypes: true
32302
33784
  })) {
32303
33785
  const match = entry.name.match(
32304
- /^(pld_[A-Za-z0-9_-]{8,96})\.(lesson|submitted|deleted)\.json$/u
33786
+ /^(pld_[A-Za-z0-9_-]{8,96})\.(lesson|submitted|deleted|replaced)\.json$/u
32305
33787
  );
32306
33788
  if (!match) continue;
32307
33789
  const draftId = match[1];
@@ -32318,10 +33800,7 @@ async function privateLessonRecoveryItems(options = {}) {
32318
33800
  outbox.encryption
32319
33801
  );
32320
33802
  const now = options.now ?? /* @__PURE__ */ new Date();
32321
- const draft = validatedDraft ? normalizeLegacyHeldSafetyDraft(
32322
- terminalizeUnsupportedProfile(validatedDraft, now),
32323
- now
32324
- ) : null;
33803
+ const draft = validatedDraft ? reconcileStoredDraft(validatedDraft, now) : null;
32325
33804
  if (draft?.state === "retry_scheduled" && draft.last_error_code === "policy_verification_failed") {
32326
33805
  items.push(
32327
33806
  privateLessonRecoveryItem(draftId, "held_safety_recovery_required")
@@ -32428,7 +33907,7 @@ function privateLessonRecoveryItem(draftId, reasonCode, storageError) {
32428
33907
  async function reconcilePrivateLessonTemporaryWrites(directory, encryption) {
32429
33908
  const groups = /* @__PURE__ */ new Map();
32430
33909
  for (const entry of await readdir(directory, { withFileTypes: true })) {
32431
- if (/^\.[a-f0-9]{24}\.capacity\.tmp$/u.test(entry.name) && entry.isFile()) {
33910
+ if (/^\.[a-f0-9]{24}\.(?:capacity|replaced)\.tmp$/u.test(entry.name) && entry.isFile()) {
32432
33911
  await unlink2(join3(directory, entry.name));
32433
33912
  continue;
32434
33913
  }
@@ -32526,6 +34005,16 @@ async function validatePrivateLessonCanonicalPath(path, name, encryption) {
32526
34005
  );
32527
34006
  return null;
32528
34007
  }
34008
+ if (name.endsWith(".replaced.json")) {
34009
+ parseReplacedRecord(
34010
+ await readPrivateLessonCanonicalText(
34011
+ path,
34012
+ PRIVATE_LESSON_SUBMITTED_RECORD_MAX_BYTES
34013
+ ),
34014
+ draftId
34015
+ );
34016
+ return null;
34017
+ }
32529
34018
  if (name.endsWith(".deleted.json")) {
32530
34019
  parseDeletionTombstone(
32531
34020
  await readPrivateLessonCanonicalText(
@@ -32666,7 +34155,7 @@ async function removeCanonicalPrivateLessonEntry(path) {
32666
34155
  async function secureOutboxEntries(directory) {
32667
34156
  const entries = await readdir(directory, { withFileTypes: true });
32668
34157
  return entries.filter(
32669
- (entry) => entry.isFile() && !entry.isSymbolicLink() && /^(?:pld_[A-Za-z0-9_-]{8,96}\.(?:lesson|submitted|deleted)\.json)$/u.test(
34158
+ (entry) => entry.isFile() && !entry.isSymbolicLink() && /^(?:pld_[A-Za-z0-9_-]{8,96}\.(?:lesson|submitted|deleted|replaced)\.json)$/u.test(
32670
34159
  entry.name
32671
34160
  )
32672
34161
  ).map((entry) => entry.name).sort();
@@ -32692,10 +34181,10 @@ async function atomicWritePrivate(path, data) {
32692
34181
  }
32693
34182
  await syncDirectory2(dirname3(path));
32694
34183
  }
32695
- async function atomicCreatePrivateLessonDraft(path, data) {
34184
+ async function atomicCreatePrivateLessonEntry(path, data, temporarySuffix = ".tmp") {
32696
34185
  const temporary = join3(
32697
34186
  dirname3(path),
32698
- `.${randomBytes4(12).toString("hex")}.tmp`
34187
+ `.${randomBytes4(12).toString("hex")}${temporarySuffix}`
32699
34188
  );
32700
34189
  try {
32701
34190
  await atomicWritePrivate(temporary, data);
@@ -32934,6 +34423,20 @@ function tombstonePath(directory, draftId) {
32934
34423
  assertDraftId(draftId);
32935
34424
  return join3(directory, `${draftId}.deleted.json`);
32936
34425
  }
34426
+ function replacedRecordPath(directory, draftId) {
34427
+ assertDraftId(draftId);
34428
+ return join3(directory, `${draftId}.replaced.json`);
34429
+ }
34430
+ function privateLessonReplacementDraftId(replacementOf, payloadDigest) {
34431
+ assertDraftId(replacementOf);
34432
+ return `pld_${hashValue(
34433
+ canonicalJson({
34434
+ domain: "remembrance-private-lesson-replacement-v1",
34435
+ replacement_of: replacementOf,
34436
+ payload_digest: payloadDigest
34437
+ })
34438
+ ).slice("sha256:".length, "sha256:".length + 32)}`;
34439
+ }
32937
34440
  function assertDraftId(value) {
32938
34441
  if (!/^pld_[A-Za-z0-9_-]{8,96}$/.test(value)) {
32939
34442
  throw new Error("Private lesson draft id is invalid.");
@@ -45344,7 +46847,7 @@ var require_timestamp = __commonJS({
45344
46847
  resolve: (str) => parseSexagesimal(str, false),
45345
46848
  stringify: stringifySexagesimal
45346
46849
  };
45347
- var timestamp = {
46850
+ var timestamp2 = {
45348
46851
  identify: (value) => value instanceof Date,
45349
46852
  default: true,
45350
46853
  tag: "tag:yaml.org,2002:timestamp",
@@ -45353,7 +46856,7 @@ var require_timestamp = __commonJS({
45353
46856
  // assumed to be 00:00:00Z (start of day, UTC).
45354
46857
  test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),
45355
46858
  resolve(str) {
45356
- const match = str.match(timestamp.test);
46859
+ const match = str.match(timestamp2.test);
45357
46860
  if (!match)
45358
46861
  throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");
45359
46862
  const [, year, month, day, hour, minute, second] = match.map(Number);
@@ -45372,7 +46875,7 @@ var require_timestamp = __commonJS({
45372
46875
  };
45373
46876
  exports.floatTime = floatTime;
45374
46877
  exports.intTime = intTime;
45375
- exports.timestamp = timestamp;
46878
+ exports.timestamp = timestamp2;
45376
46879
  }
45377
46880
  });
45378
46881
  var require_schema3 = __commonJS({
@@ -45390,7 +46893,7 @@ var require_schema3 = __commonJS({
45390
46893
  var omap = require_omap();
45391
46894
  var pairs = require_pairs();
45392
46895
  var set = require_set();
45393
- var timestamp = require_timestamp();
46896
+ var timestamp2 = require_timestamp();
45394
46897
  var schema = [
45395
46898
  map.map,
45396
46899
  seq.seq,
@@ -45410,9 +46913,9 @@ var require_schema3 = __commonJS({
45410
46913
  omap.omap,
45411
46914
  pairs.pairs,
45412
46915
  set.set,
45413
- timestamp.intTime,
45414
- timestamp.floatTime,
45415
- timestamp.timestamp
46916
+ timestamp2.intTime,
46917
+ timestamp2.floatTime,
46918
+ timestamp2.timestamp
45416
46919
  ];
45417
46920
  exports.schema = schema;
45418
46921
  }
@@ -45435,7 +46938,7 @@ var require_tags = __commonJS({
45435
46938
  var pairs = require_pairs();
45436
46939
  var schema$2 = require_schema3();
45437
46940
  var set = require_set();
45438
- var timestamp = require_timestamp();
46941
+ var timestamp2 = require_timestamp();
45439
46942
  var schemas = /* @__PURE__ */ new Map([
45440
46943
  ["core", schema.schema],
45441
46944
  ["failsafe", [map.map, seq.seq, string.string]],
@@ -45449,11 +46952,11 @@ var require_tags = __commonJS({
45449
46952
  float: float.float,
45450
46953
  floatExp: float.floatExp,
45451
46954
  floatNaN: float.floatNaN,
45452
- floatTime: timestamp.floatTime,
46955
+ floatTime: timestamp2.floatTime,
45453
46956
  int: int.int,
45454
46957
  intHex: int.intHex,
45455
46958
  intOct: int.intOct,
45456
- intTime: timestamp.intTime,
46959
+ intTime: timestamp2.intTime,
45457
46960
  map: map.map,
45458
46961
  merge: merge.merge,
45459
46962
  null: _null.nullTag,
@@ -45461,7 +46964,7 @@ var require_tags = __commonJS({
45461
46964
  pairs: pairs.pairs,
45462
46965
  seq: seq.seq,
45463
46966
  set: set.set,
45464
- timestamp: timestamp.timestamp
46967
+ timestamp: timestamp2.timestamp
45465
46968
  };
45466
46969
  var coreKnownTags = {
45467
46970
  "tag:yaml.org,2002:binary": binary.binary,
@@ -45469,7 +46972,7 @@ var require_tags = __commonJS({
45469
46972
  "tag:yaml.org,2002:omap": omap.omap,
45470
46973
  "tag:yaml.org,2002:pairs": pairs.pairs,
45471
46974
  "tag:yaml.org,2002:set": set.set,
45472
- "tag:yaml.org,2002:timestamp": timestamp.timestamp
46975
+ "tag:yaml.org,2002:timestamp": timestamp2.timestamp
45473
46976
  };
45474
46977
  function getTags(customTags, schemaName, addMergeTag) {
45475
46978
  const schemaTags = schemas.get(schemaName);
@@ -65226,7 +66729,8 @@ var LOCAL_ONLY_HANDLERS = Object.freeze({
65226
66729
  ),
65227
66730
  inspect_private_lesson_outbox: (payload, context) => inspectPrivateLessonOutbox(
65228
66731
  payload,
65229
- context.persistence
66732
+ context.persistence,
66733
+ context.privateLessonDestination
65230
66734
  ),
65231
66735
  delete_private_lesson_candidate: (payload, context) => {
65232
66736
  const request = payload;
@@ -65313,19 +66817,64 @@ function acknowledgeFeedbackDenialLocally(input, persistence) {
65313
66817
  };
65314
66818
  }
65315
66819
  }
65316
- async function preparePrivateLessonDraft(input, persistence, destination, tool) {
66820
+ async function preparePrivateLessonDraft(input, persistence, destination, tool, replacementOf) {
65317
66821
  const prepared = preparePrivateLessonCandidate(input, { tool });
66822
+ if (replacementOf) {
66823
+ return preparePrivateLessonReplacement(
66824
+ input,
66825
+ prepared,
66826
+ replacementOf,
66827
+ persistence,
66828
+ destination
66829
+ );
66830
+ }
65318
66831
  const draft = await persistence.queuePreparedPrivateLesson(
65319
66832
  prepared,
65320
66833
  destination
65321
66834
  );
65322
- return privateLessonDraftActionResult(draft, {
66835
+ return privateLessonDraftActionResult(draft, destination, {
65323
66836
  next_action: prepared.status === "ready" || prepared.status === "held_safety" && privateLessonHealthReportingEnabled() ? {
65324
66837
  tool: "submit_private_lesson_candidate",
65325
66838
  arguments: { draft_id: draft.draft_id }
65326
- } : null
66839
+ } : null,
66840
+ // Where the lesson holds, without its text, for a replacement.
66841
+ ...prepared.status === "held_safety" ? privateLessonFindings(input) : {}
65327
66842
  });
65328
66843
  }
66844
+ async function preparePrivateLessonReplacement(input, prepared, replacementOf, persistence, destination) {
66845
+ try {
66846
+ const { draft, attempts_remaining, replayed } = await persistence.queuePrivateLessonReplacement(
66847
+ replacementOf,
66848
+ prepared,
66849
+ destination
66850
+ );
66851
+ return privateLessonDraftActionResult(draft, destination, {
66852
+ replacement_attempts_remaining: attempts_remaining,
66853
+ replayed,
66854
+ ...draft.state === "awaiting_authorization" && draft.attempts === 0 ? {
66855
+ next_action: {
66856
+ tool: "submit_private_lesson_candidate",
66857
+ arguments: { draft_id: draft.draft_id }
66858
+ }
66859
+ } : {}
66860
+ });
66861
+ } catch (error) {
66862
+ if (!(error instanceof PrivateLessonReplacementRefusedError) || error.reason !== "replacement_held") {
66863
+ throw error;
66864
+ }
66865
+ return {
66866
+ status: "not_stored",
66867
+ ...error.diagnostic(),
66868
+ held_reasons: prepared.held_reasons,
66869
+ ...privateLessonFindings(input),
66870
+ agent_recovery: privateLessonAgentRecovery(
66871
+ replacementOf,
66872
+ error.attemptsRemaining
66873
+ ),
66874
+ action_required: error.attemptsRemaining > 0 ? `The local safety check holds this version too (held_reasons and findings), so it was not stored or sent, and the held draft stays as it is. Write a version without what the findings name and capture it again with the same replacement_of; ${error.attemptsRemaining} attempt${error.attemptsRemaining === 1 ? "" : "s"} left.` : privateLessonHeldRecoveryActionRequired(0)
66875
+ };
66876
+ }
66877
+ }
65329
66878
  async function captureLearning(input, persistence, lessonDestination, skillDestination) {
65330
66879
  const parsed = captureLearningInputSchema.parse(input);
65331
66880
  const route = captureLearningRoute(parsed);
@@ -65341,11 +66890,12 @@ async function captureLearning(input, persistence, lessonDestination, skillDesti
65341
66890
  };
65342
66891
  }
65343
66892
  if (route === "private_skill") {
65344
- const draft = parsed.replacement_of ? await persistence.queuePrivateSkillReformulation(
65345
- parsed.replacement_of.draft_id,
66893
+ const link2 = parsed.replacement_of && "context_source" in parsed.replacement_of ? parsed.replacement_of : void 0;
66894
+ const draft = link2 ? await persistence.queuePrivateSkillReformulation(
66895
+ link2.draft_id,
65346
66896
  parsed.private_skill,
65347
- parsed.replacement_of.context_source,
65348
- ...parsed.replacement_of.recovery_context_id ? [parsed.replacement_of.recovery_context_id] : []
66897
+ link2.context_source,
66898
+ ...link2.recovery_context_id ? [link2.recovery_context_id] : []
65349
66899
  ) : await persistence.queuePrivateSkillCapture(
65350
66900
  parsed.private_skill,
65351
66901
  skillDestination
@@ -65364,7 +66914,8 @@ async function captureLearning(input, persistence, lessonDestination, skillDesti
65364
66914
  parsed.lesson,
65365
66915
  persistence,
65366
66916
  lessonDestination,
65367
- "capture_learning"
66917
+ "capture_learning",
66918
+ parsed.replacement_of?.draft_id
65368
66919
  );
65369
66920
  return {
65370
66921
  contract_version: parsed.contract_version,
@@ -65471,7 +67022,7 @@ function privateOutboxDiagnostic(error) {
65471
67022
  const { reason_code, stage, remediation } = error.diagnostic();
65472
67023
  return { reason_code, stage, remediation };
65473
67024
  }
65474
- async function inspectPrivateLessonOutbox(input, persistence) {
67025
+ async function inspectPrivateLessonOutbox(input, persistence, destination) {
65475
67026
  const snapshot = await persistence.inspectPrivateLessonOutbox(
65476
67027
  input.limit,
65477
67028
  input.offset
@@ -65490,7 +67041,7 @@ async function inspectPrivateLessonOutbox(input, persistence) {
65490
67041
  }
65491
67042
  const draft = await persistence.readPrivateLessonDraft(input.draft_id);
65492
67043
  return {
65493
- draft: privateLessonDraftActionResult(draft),
67044
+ draft: privateLessonDraftActionResult(draft, destination),
65494
67045
  outbox: publicOutboxSummary(snapshot.summary),
65495
67046
  recovery_items: snapshot.recovery_items
65496
67047
  };
@@ -65548,7 +67099,7 @@ function privateLessonSelectedDraftError(draftId, error) {
65548
67099
  function privateLessonHealthReportingEnabled(env = process.env) {
65549
67100
  return !/^(0|false|no)$/i.test(env.REMEMBRANCE_HEALTH_REPORTING ?? "");
65550
67101
  }
65551
- function privateLessonDraftActionResult(draft, extra = {}) {
67102
+ function privateLessonDraftActionResult(draft, destination, extra = {}) {
65552
67103
  return {
65553
67104
  draft_id: draft.draft_id,
65554
67105
  state: draft.state,
@@ -65565,8 +67116,10 @@ function privateLessonDraftActionResult(draft, extra = {}) {
65565
67116
  hold_event_digest: draft.hold_event_digest,
65566
67117
  hold_receipt_digest: draft.hold_receipt_digest,
65567
67118
  hold_reported_at: draft.hold_reported_at,
67119
+ ...safetyRecheckField(draft),
67120
+ ...privateLessonRecoveryFields(draft, destination),
65568
67121
  retained_locally: draft.state !== "submitted" || hasUnverifiablePrivateLessonCompletion(draft),
65569
- action_required: privateLessonActionRequired(draft),
67122
+ action_required: privateLessonActionRequired(draft, destination),
65570
67123
  next_action: privateLessonNextAction(draft),
65571
67124
  ...extra
65572
67125
  };
@@ -65614,7 +67167,8 @@ function privateLessonNextAction(draft) {
65614
67167
  }
65615
67168
  return null;
65616
67169
  }
65617
- function privateLessonActionRequired(draft) {
67170
+ var PRIVATE_LESSON_RECHECKED_HOLD_DECISION = "An earlier safety check held this draft and the current one would not. It stays held unless the user chooses to deliver it (retry_private_lesson_candidate with deliver_rechecked_hold=true) or to delete it (delete_private_lesson_candidate with confirm=true); keeping it needs no action.";
67171
+ function privateLessonActionRequired(draft, destination) {
65618
67172
  if (hasUnverifiablePrivateLessonCompletion(draft)) {
65619
67173
  return PRIVATE_LESSON_UNVERIFIABLE_COMPLETION_REMEDIATION;
65620
67174
  }
@@ -65624,6 +67178,15 @@ function privateLessonActionRequired(draft) {
65624
67178
  if (draft.state === "held_safety" && draft.held_reasons.length === 0) {
65625
67179
  return "This legacy safety hold has no classified content reason. Retry the exact retained draft so current policy validation can recover it; no replacement has been submitted.";
65626
67180
  }
67181
+ if (privateLessonSafetyRecheck(draft)) {
67182
+ return PRIVATE_LESSON_RECHECKED_HOLD_DECISION;
67183
+ }
67184
+ if (draft.state === "held_safety" && privateLessonReplaceable(draft)) {
67185
+ return privateLessonHeldRecoveryActionRequired(
67186
+ privateLessonReplacementAttemptsRemaining(draft),
67187
+ !privateLessonReplaceable(draft, destination)
67188
+ );
67189
+ }
65627
67190
  if (draft.state === "awaiting_authorization") {
65628
67191
  return "Restore authorization for the exact private-lesson submission action, then retry this retained draft.";
65629
67192
  }
@@ -65642,6 +67205,9 @@ function privateLessonActionRequired(draft) {
65642
67205
  if (draft.state === "held_validation" && draft.last_error_code === "private_lesson_destination_audience_mismatch") {
65643
67206
  return "The current credential proves a different organization audience. Restore the captured organization destination; the retained draft was not sent to this one.";
65644
67207
  }
67208
+ if (draft.state === "held_validation" && draft.last_error_code === "private_lesson_destination_attestation_mismatch") {
67209
+ return PRIVATE_LESSON_ATTESTATION_MISMATCH_REMEDIATION;
67210
+ }
65645
67211
  if (draft.state === "held_validation") {
65646
67212
  return "The encrypted draft remains local because the response or draft failed validation. Inspect its content-free state before choosing any further action; it will not be retried automatically.";
65647
67213
  }
@@ -66187,6 +67753,10 @@ function createLocalPersistenceCapabilities(dependencies = {}) {
66187
67753
  ...await withEncryption(),
66188
67754
  ...destination ? { destination } : {}
66189
67755
  }),
67756
+ queuePrivateLessonReplacement: async (replacementOf, prepared, destination) => queuePrivateLessonReplacement(replacementOf, prepared, {
67757
+ ...await withEncryption(),
67758
+ ...destination ? { destination } : {}
67759
+ }),
66190
67760
  queuePrivateSkillCapture: async (candidate, destination) => queuePrivateSkillCapture(candidate, {
66191
67761
  ...await withEncryption(),
66192
67762
  ...destination ? { destination } : {}
@@ -66230,9 +67800,68 @@ function createLocalPersistenceCapabilities(dependencies = {}) {
66230
67800
  });
66231
67801
  }
66232
67802
 
66233
- // src/network-transport.ts
67803
+ // ../core/src/redaction-request-budget.ts
66234
67804
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
66235
- var networkExecutionAuthority = new AsyncLocalStorage2();
67805
+ var requests = new AsyncLocalStorage2();
67806
+ trackRedactionRequests(() => requests.getStore());
67807
+ function withRedactionRequestBudget(run) {
67808
+ return requests.getStore() ? run() : requests.run({}, run);
67809
+ }
67810
+
67811
+ // src/review-repair-inspection.ts
67812
+ function inspectReviewRepairForTransport(value) {
67813
+ const request = privateSkillReviewRepairRequestSchema.parse(value);
67814
+ const inspection = inspectPrivateSkillCandidate(request.capture);
67815
+ if (inspection.status === "complete" && inspection.decision.outcome === "unchanged") {
67816
+ const values = [];
67817
+ const pending = [request.expected_review_snapshot];
67818
+ while (pending.length) {
67819
+ const entry = pending.pop();
67820
+ if (entry !== null && typeof entry === "object") pending.push(...Object.values(entry));
67821
+ else values.push(entry);
67822
+ }
67823
+ try {
67824
+ if (canonicalJson(withRedactionRequestBudget(() => redactPayload(values))) !== canonicalJson(values)) {
67825
+ return { ready: false, refusal: {
67826
+ status: "held",
67827
+ code: "review_repair_wire_inspection_hold",
67828
+ delivery: "not_delivered",
67829
+ candidate_sent: false,
67830
+ candidate_stored: false,
67831
+ original_disposition: "unchanged",
67832
+ next_action: "Retain the original. Read a fresh normal content-free review snapshot; do not send suspected secrets, rewrite the held request, or use another transport."
67833
+ } };
67834
+ }
67835
+ } catch {
67836
+ return { ready: false, refusal: {
67837
+ status: "held",
67838
+ code: "review_repair_wire_inspection_failure",
67839
+ delivery: "not_delivered",
67840
+ candidate_sent: false,
67841
+ candidate_stored: false,
67842
+ original_disposition: "unchanged",
67843
+ next_action: "Retain the original. Correct the local inspection failure before retrying; do not reformulate around an operational failure."
67844
+ } };
67845
+ }
67846
+ return { ready: true, request };
67847
+ }
67848
+ const reason = inspection.status === "complete" ? "authored_capture_changed_by_inspection" : inspection.status === "incomplete" ? inspection.reason : inspection.error_code;
67849
+ return { ready: false, refusal: {
67850
+ status: "held",
67851
+ code: "review_repair_local_inspection_hold",
67852
+ delivery: "not_delivered",
67853
+ candidate_sent: false,
67854
+ candidate_stored: false,
67855
+ original_disposition: "unchanged",
67856
+ reason_code: reason,
67857
+ inspection: inspection.decision,
67858
+ next_action: inspection.status === "invalid" ? "Retain the original. Correct the local inspection failure before retrying the same unchanged request; do not reformulate around an operational failure or use another transport." : "Retain the original. Prepare a complete safe replacement from authenticated task context and inspect it again. Do not recover suspected secrets, invent missing instructions, or bypass a host denial."
67859
+ } };
67860
+ }
67861
+
67862
+ // src/network-transport.ts
67863
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
67864
+ var networkExecutionAuthority = new AsyncLocalStorage3();
66236
67865
  var guardedFetches = /* @__PURE__ */ new WeakSet();
66237
67866
  function installRuntimeFetchGuard() {
66238
67867
  const delegate = globalThis.fetch;
@@ -67529,6 +69158,17 @@ function localPluginLifecycleHealth(options) {
67529
69158
  explanation: "Each host process session is tracked independently. Turn-specific prompt, tool, and completion observations are combined only when they share the current SessionStart marker."
67530
69159
  };
67531
69160
  }
69161
+ var HOOK_TRUST_UNAVAILABLE_REASONS = /* @__PURE__ */ new Set([
69162
+ "app_server_closed",
69163
+ "app_server_initialize_failed",
69164
+ "app_server_unavailable",
69165
+ "check_disabled",
69166
+ "codex_executable_not_found",
69167
+ "hooks_list_failed",
69168
+ "hooks_list_timeout",
69169
+ "hooks_list_too_large",
69170
+ "plugin_hooks_not_listed"
69171
+ ]);
67532
69172
  function normalizedPluginHookTrust(value) {
67533
69173
  if (!isRecord9(value)) return null;
67534
69174
  const status = value.status;
@@ -67563,7 +69203,8 @@ function normalizedPluginHookTrust(value) {
67563
69203
  status,
67564
69204
  checked_at: typeof value.checked_at === "string" && Number.isFinite(Date.parse(value.checked_at)) ? new Date(value.checked_at).toISOString() : null,
67565
69205
  review_events: reviewEvents,
67566
- hooks
69206
+ hooks,
69207
+ reason: status === "unavailable" && typeof value.reason === "string" && HOOK_TRUST_UNAVAILABLE_REASONS.has(value.reason) ? value.reason : null
67567
69208
  };
67568
69209
  }
67569
69210
  function apiDestinationStatus(baseUrl, source) {
@@ -67945,7 +69586,7 @@ function inspectPrivateLearningOutbox2(input, dependencies = {}) {
67945
69586
  }
67946
69587
  var MAX_REMOTE_RESPONSE_BYTES = 4 * 1024 * 1024;
67947
69588
  var DOCTOR_PROBE_TIMEOUT_MS = 7500;
67948
- var SERVER_VERSION = true ? "0.2.4" : "0.0.0-dev";
69589
+ var SERVER_VERSION = true ? "0.2.6" : "0.0.0-dev";
67949
69590
  var tools2 = toolDefinitions;
67950
69591
  var doctorCliRequested = process.argv[2] === "doctor";
67951
69592
  var nativeContextCliRequested = process.argv[2] === "--native-context";
@@ -68226,6 +69867,9 @@ function jsonRpcErrorForToolError(error) {
68226
69867
  data: error.diagnostic()
68227
69868
  };
68228
69869
  }
69870
+ if (error instanceof PrivateLessonReplacementRefusedError) {
69871
+ return { code: -32602, message: error.message, data: error.diagnostic() };
69872
+ }
68229
69873
  if (error instanceof PrivateLessonLengthLimitError || error instanceof PrivateSkillSizeLimitError) {
68230
69874
  return { code: -32602, message: error.message, data: error.diagnostic() };
68231
69875
  }
@@ -68304,15 +69948,22 @@ async function callToolWithinExecution(runtimeDefinition, rawArguments, dependen
68304
69948
  );
68305
69949
  }
68306
69950
  async function callNetworkToolWithinExecution(definition, payload, access, transport) {
69951
+ if (definition.name === "repair_review_draft") {
69952
+ const inspection = inspectReviewRepairForTransport(payload);
69953
+ if (!inspection.ready) return inspection.refusal;
69954
+ payload = inspection.request;
69955
+ }
68307
69956
  if (definition.local === "bootstrap_agent_identity") {
68308
69957
  return bootstrapAgentIdentity(payload, access, transport);
68309
69958
  }
68310
69959
  if (definition.local === "retry_private_lesson_candidate") {
69960
+ const args = payload;
68311
69961
  return submitPrivateLessonDraft(
68312
- String(payload.draft_id),
69962
+ String(args.draft_id),
68313
69963
  access,
68314
69964
  "retry",
68315
- transport
69965
+ transport,
69966
+ { deliverRecheckedHold: args.deliver_rechecked_hold === true }
68316
69967
  );
68317
69968
  }
68318
69969
  if (definition.local === "retry_private_skill_candidate") {
@@ -68365,7 +70016,11 @@ async function callNetworkToolWithinExecution(definition, payload, access, trans
68365
70016
  access.credential.source,
68366
70017
  access.configuration.issue
68367
70018
  );
68368
- const result = definition.name === "get_connection_status" && localConfigurationError ? { ok: false, status: 0, error: localConfigurationError } : await callRemembrance(definition, payload, { access, transport });
70019
+ const result = definition.name === "get_connection_status" && localConfigurationError ? { ok: false, status: 0, error: localConfigurationError } : await callRemembrance(definition, payload, {
70020
+ access,
70021
+ transport,
70022
+ ...["get_review_comparison", "repair_review_draft"].includes(definition.name) ? { redirect: "manual" } : {}
70023
+ });
68369
70024
  if (definition.name === "get_connection_status") {
68370
70025
  const status = localConnectionStatus(result, {
68371
70026
  apiBase: access.configuration.baseUrl,
@@ -68580,11 +70235,11 @@ function retryAfterDelayMs(value, nowMs = Date.now()) {
68580
70235
  Number(trimmed) * 1e3
68581
70236
  );
68582
70237
  }
68583
- const timestamp = Date.parse(trimmed);
68584
- if (!Number.isFinite(timestamp)) return null;
70238
+ const timestamp2 = Date.parse(trimmed);
70239
+ if (!Number.isFinite(timestamp2)) return null;
68585
70240
  return Math.min(
68586
70241
  PRIVATE_LEARNING_MAX_RETRY_DELAY_MS,
68587
- Math.max(0, timestamp - nowMs)
70242
+ Math.max(0, timestamp2 - nowMs)
68588
70243
  );
68589
70244
  }
68590
70245
  function privateLessonDestinationForAccess(access) {
@@ -69393,6 +71048,9 @@ var RECOVERABLE_PRIVATE_LESSON_DESTINATION_ERRORS = /* @__PURE__ */ new Set([
69393
71048
  "private_lesson_destination_audience_mismatch"
69394
71049
  ]);
69395
71050
  function privateLessonDestinationError(draft, current) {
71051
+ if (draft.state === "held_validation" && draft.last_error_code === "private_lesson_destination_attestation_mismatch") {
71052
+ return "private_lesson_destination_attestation_mismatch";
71053
+ }
69396
71054
  const captured = draft.destination_binding;
69397
71055
  if (!captured) return "private_lesson_destination_legacy_unbound";
69398
71056
  if (captured.api_base_sha256 !== current.api_base_sha256) {
@@ -69413,17 +71071,22 @@ function privateLessonDestinationActionRequired(code) {
69413
71071
  return "The credential differs from capture and no verified organization audience was established. Restore the captured credential and API base, then retry the exact retained draft.";
69414
71072
  case "private_lesson_destination_audience_mismatch":
69415
71073
  return "The current credential proves a different organization audience. Restore the captured organization destination; the retained draft was not sent to this one.";
71074
+ case "private_lesson_destination_attestation_mismatch":
71075
+ return PRIVATE_LESSON_ATTESTATION_MISMATCH_REMEDIATION;
69416
71076
  }
69417
71077
  }
69418
71078
  function privateLessonDestinationNextAction(draftId, code) {
69419
- return code === "private_lesson_destination_legacy_unbound" ? {
69420
- tool: "capture_learning",
69421
- action_code: "recapture_legacy_private_lesson_with_destination_binding",
69422
- retained_source_draft_id: draftId,
69423
- retained_source_available_to_agent: false,
69424
- required_input: ["lesson"]
69425
- } : {
69426
- tool: "retry_private_lesson_candidate",
71079
+ if (code === "private_lesson_destination_legacy_unbound") {
71080
+ return {
71081
+ tool: "capture_learning",
71082
+ action_code: "recapture_legacy_private_lesson_with_destination_binding",
71083
+ retained_source_draft_id: draftId,
71084
+ retained_source_available_to_agent: false,
71085
+ required_input: ["lesson"]
71086
+ };
71087
+ }
71088
+ return {
71089
+ tool: code === "private_lesson_destination_attestation_mismatch" ? "inspect_private_lesson_outbox" : "retry_private_lesson_candidate",
69427
71090
  arguments: { draft_id: draftId }
69428
71091
  };
69429
71092
  }
@@ -69436,8 +71099,9 @@ async function holdPrivateLessonDestination(draft, code) {
69436
71099
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
69437
71100
  }));
69438
71101
  }
69439
- async function submitPrivateLessonDraft(draftId, access, mode, transport) {
71102
+ async function submitPrivateLessonDraft(draftId, access, mode, transport, { deliverRecheckedHold = false } = {}) {
69440
71103
  const allowPolicyRefresh = mode === "retry";
71104
+ const currentDestination = privateLessonDestinationForAccess(access);
69441
71105
  const source = await readPrivateLessonSubmissionSource(draftId);
69442
71106
  if (source.kind === "submitted") {
69443
71107
  return privateLessonSubmittedActionResult2(source.completion, {
@@ -69446,7 +71110,7 @@ async function submitPrivateLessonDraft(draftId, access, mode, transport) {
69446
71110
  }
69447
71111
  let draft = source.draft;
69448
71112
  if (draft.state === "superseded_redactor") {
69449
- return privateLessonDraftActionResult2(draft, {
71113
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69450
71114
  status: "superseded_redactor",
69451
71115
  action_required: privateLessonDraftActionRequired(draft)
69452
71116
  });
@@ -69467,6 +71131,24 @@ async function submitPrivateLessonDraft(draftId, access, mode, transport) {
69467
71131
  status: "already_submitted"
69468
71132
  });
69469
71133
  }
71134
+ if (deliverRecheckedHold && draft.state === "held_safety" && draft.held_reasons.length > 0) {
71135
+ try {
71136
+ draft = await releaseRecheckedPrivateLessonHold(draft.draft_id);
71137
+ } catch (error) {
71138
+ if (!(error instanceof PrivateLessonHoldReleaseRefusedError)) throw error;
71139
+ return privateLessonDraftActionResult2(draft, currentDestination, {
71140
+ status: "not_submitted",
71141
+ error_code: "private_lesson_hold_not_released",
71142
+ current_hold_reasons: [...error.holdReasons],
71143
+ // Not sent: replacing it is the way on, as for any held draft.
71144
+ action_required: privateLessonHeldRecoveryActionRequired(
71145
+ privateLessonReplacementAttemptsRemaining(draft),
71146
+ !privateLessonReplaceable(draft, currentDestination)
71147
+ ),
71148
+ candidate_sent: false
71149
+ });
71150
+ }
71151
+ }
69470
71152
  if (draft.state === "held_safety" && draft.held_reasons.length === 0) {
69471
71153
  draft = await updatePrivateLessonDraft(
69472
71154
  draft.draft_id,
@@ -69483,14 +71165,13 @@ async function submitPrivateLessonDraft(draftId, access, mode, transport) {
69483
71165
  } : current
69484
71166
  );
69485
71167
  }
69486
- const currentDestination = privateLessonDestinationForAccess(access);
69487
71168
  const destinationError = privateLessonDestinationError(
69488
71169
  draft,
69489
71170
  currentDestination
69490
71171
  );
69491
71172
  if (destinationError) {
69492
71173
  draft = await holdPrivateLessonDestination(draft, destinationError);
69493
- return privateLessonDraftActionResult2(draft, {
71174
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69494
71175
  status: "not_submitted",
69495
71176
  action_required: privateLessonDestinationActionRequired(destinationError),
69496
71177
  next_action: privateLessonDestinationNextAction(
@@ -69500,10 +71181,27 @@ async function submitPrivateLessonDraft(draftId, access, mode, transport) {
69500
71181
  candidate_sent: false
69501
71182
  });
69502
71183
  }
69503
- if (mode === "retry") {
71184
+ const restoredHold = draft.held_reasons.length > 0 && draft.state !== "held_safety";
71185
+ if (restoredHold) {
71186
+ draft = await updatePrivateLessonDraft(
71187
+ draft.draft_id,
71188
+ (current) => current.held_reasons.length > 0 && current.state !== "held_safety" && current.state !== "submitted" && current.state !== "superseded_redactor" ? {
71189
+ ...current,
71190
+ state: "held_safety",
71191
+ next_retry_at: null,
71192
+ last_error_code: null,
71193
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
71194
+ } : current
71195
+ );
71196
+ }
71197
+ if (mode === "retry" && !restoredHold) {
69504
71198
  const retryGate = privateLessonRetryGate(draft);
69505
71199
  if (retryGate) {
69506
- return privateLessonDraftActionResult2(draft, retryGate);
71200
+ return privateLessonDraftActionResult2(
71201
+ draft,
71202
+ currentDestination,
71203
+ retryGate
71204
+ );
69507
71205
  }
69508
71206
  }
69509
71207
  if (draft.state === "held_safety") {
@@ -69540,7 +71238,7 @@ async function submitPrivateLessonDraft(draftId, access, mode, transport) {
69540
71238
  error,
69541
71239
  error instanceof PrivateLessonPolicyFloorError ? error.code : void 0
69542
71240
  );
69543
- return privateLessonDraftActionResult2(draft, {
71241
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69544
71242
  status: "not_submitted",
69545
71243
  action_required: privateLessonDraftActionRequired(draft)
69546
71244
  });
@@ -69548,7 +71246,17 @@ async function submitPrivateLessonDraft(draftId, access, mode, transport) {
69548
71246
  if (draft.destination_binding && draft.destination_binding.credential_sha256 !== currentDestination.credential_sha256 && draft.policy && draft.policy.organization_audience_hash !== currentBinding.organization_audience_hash) {
69549
71247
  const code = "private_lesson_destination_audience_mismatch";
69550
71248
  draft = await holdPrivateLessonDestination(draft, code);
69551
- return privateLessonDraftActionResult2(draft, {
71249
+ return privateLessonDraftActionResult2(draft, currentDestination, {
71250
+ status: "not_submitted",
71251
+ action_required: privateLessonDestinationActionRequired(code),
71252
+ next_action: privateLessonDestinationNextAction(draft.draft_id, code),
71253
+ candidate_sent: false
71254
+ });
71255
+ }
71256
+ if (draft.attested_organization_audience_hash !== void 0 && draft.attested_organization_audience_hash !== currentBinding.organization_audience_hash) {
71257
+ const code = "private_lesson_destination_attestation_mismatch";
71258
+ draft = await holdPrivateLessonDestination(draft, code);
71259
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69552
71260
  status: "not_submitted",
69553
71261
  action_required: privateLessonDestinationActionRequired(code),
69554
71262
  next_action: privateLessonDestinationNextAction(draft.draft_id, code),
@@ -69566,7 +71274,7 @@ async function submitPrivateLessonDraft(draftId, access, mode, transport) {
69566
71274
  ),
69567
71275
  "organization_policy_disabled"
69568
71276
  );
69569
- return privateLessonDraftActionResult2(draft, {
71277
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69570
71278
  status: "not_submitted",
69571
71279
  action_required: privateLessonDraftActionRequired(draft)
69572
71280
  });
@@ -69579,7 +71287,7 @@ async function submitPrivateLessonDraft(draftId, access, mode, transport) {
69579
71287
  "payload_limit_unavailable"
69580
71288
  )
69581
71289
  );
69582
- return privateLessonDraftActionResult2(draft, {
71290
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69583
71291
  status: "not_submitted",
69584
71292
  action_required: privateLessonDraftActionRequired(draft)
69585
71293
  });
@@ -69595,7 +71303,7 @@ async function submitPrivateLessonDraft(draftId, access, mode, transport) {
69595
71303
  new PrivateLessonPolicyHoldError(policyConflict.message),
69596
71304
  policyConflict.code
69597
71305
  );
69598
- return privateLessonDraftActionResult2(draft, {
71306
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69599
71307
  status: "not_submitted",
69600
71308
  action_required: policyConflict.action_required
69601
71309
  });
@@ -69708,7 +71416,7 @@ async function submitPrivateLessonDraft(draftId, access, mode, transport) {
69708
71416
  updated_at: completion.updated_at
69709
71417
  };
69710
71418
  return {
69711
- ...privateLessonDraftActionResult2(draft, {
71419
+ ...privateLessonDraftActionResult2(draft, currentDestination, {
69712
71420
  status,
69713
71421
  completion_expires_at: completion.expires_at
69714
71422
  }),
@@ -69718,11 +71426,11 @@ async function submitPrivateLessonDraft(draftId, access, mode, transport) {
69718
71426
  } catch (error) {
69719
71427
  draft = await persistPrivateLessonFailure(draft, error);
69720
71428
  if (draft.state === "submitted") {
69721
- return privateLessonDraftActionResult2(draft, {
71429
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69722
71430
  status: "already_submitted"
69723
71431
  });
69724
71432
  }
69725
- return privateLessonDraftActionResult2(draft, {
71433
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69726
71434
  status: "not_submitted",
69727
71435
  action_required: privateLessonDraftActionRequired(draft)
69728
71436
  });
@@ -69786,13 +71494,14 @@ function privateLessonRetryGate(draft) {
69786
71494
  }
69787
71495
  function retryDue(nextRetryAt) {
69788
71496
  if (!nextRetryAt) return true;
69789
- const timestamp = Date.parse(nextRetryAt);
69790
- return !Number.isFinite(timestamp) || timestamp <= Date.now();
71497
+ const timestamp2 = Date.parse(nextRetryAt);
71498
+ return !Number.isFinite(timestamp2) || timestamp2 <= Date.now();
69791
71499
  }
69792
71500
  async function submitPrivateLessonHoldTelemetry(initialDraft, access, allowPolicyRefresh, transport) {
69793
71501
  let draft = initialDraft;
71502
+ const currentDestination = privateLessonDestinationForAccess(access);
69794
71503
  if (draft.hold_telemetry_status === "submitted") {
69795
- return privateLessonDraftActionResult2(draft, {
71504
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69796
71505
  status: "already_recorded",
69797
71506
  processing_state: "recorded"
69798
71507
  });
@@ -69804,7 +71513,7 @@ async function submitPrivateLessonHoldTelemetry(initialDraft, access, allowPolic
69804
71513
  next_retry_at: null,
69805
71514
  last_error_code: "health_reporting_disabled"
69806
71515
  }));
69807
- return privateLessonDraftActionResult2(draft, {
71516
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69808
71517
  status: "not_submitted",
69809
71518
  action_required: null
69810
71519
  });
@@ -69824,7 +71533,7 @@ async function submitPrivateLessonHoldTelemetry(initialDraft, access, allowPolic
69824
71533
  );
69825
71534
  } catch (error) {
69826
71535
  draft = await persistPrivateLessonHoldFailure(draft, error);
69827
- return privateLessonDraftActionResult2(draft, {
71536
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69828
71537
  status: "not_submitted",
69829
71538
  action_required: privateLessonHoldActionRequired(draft)
69830
71539
  });
@@ -69837,7 +71546,7 @@ async function submitPrivateLessonHoldTelemetry(initialDraft, access, allowPolic
69837
71546
  next_retry_at: null,
69838
71547
  last_error_code: "private_lesson_automation_disabled"
69839
71548
  }));
69840
- return privateLessonDraftActionResult2(draft, {
71549
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69841
71550
  status: "not_submitted",
69842
71551
  action_required: null
69843
71552
  });
@@ -69853,7 +71562,7 @@ async function submitPrivateLessonHoldTelemetry(initialDraft, access, allowPolic
69853
71562
  new PrivateLessonPolicyHoldError(policyConflict.message),
69854
71563
  policyConflict.code
69855
71564
  );
69856
- return privateLessonDraftActionResult2(draft, {
71565
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69857
71566
  status: "not_submitted",
69858
71567
  action_required: policyConflict.action_required
69859
71568
  });
@@ -69898,7 +71607,7 @@ async function submitPrivateLessonHoldTelemetry(initialDraft, access, allowPolic
69898
71607
  policy: receiptPolicy
69899
71608
  }));
69900
71609
  return {
69901
- ...privateLessonDraftActionResult2(draft, {
71610
+ ...privateLessonDraftActionResult2(draft, currentDestination, {
69902
71611
  status: submitted.status
69903
71612
  }),
69904
71613
  receipt: submitted.receipt,
@@ -69910,7 +71619,7 @@ async function submitPrivateLessonHoldTelemetry(initialDraft, access, allowPolic
69910
71619
  continue;
69911
71620
  }
69912
71621
  draft = await persistPrivateLessonHoldFailure(draft, error);
69913
- return privateLessonDraftActionResult2(draft, {
71622
+ return privateLessonDraftActionResult2(draft, currentDestination, {
69914
71623
  status: "not_submitted",
69915
71624
  action_required: privateLessonHoldActionRequired(draft)
69916
71625
  });
@@ -70387,7 +72096,7 @@ function privateLessonRetryAt(attempts, retryAfterMs = null) {
70387
72096
  Date.now() + Math.max(privateLessonRetryDelayMs(attempts), retryAfterMs ?? 0)
70388
72097
  ).toISOString();
70389
72098
  }
70390
- function privateLessonDraftActionResult2(draft, extra = {}) {
72099
+ function privateLessonDraftActionResult2(draft, destination, extra = {}) {
70391
72100
  return {
70392
72101
  draft_id: draft.draft_id,
70393
72102
  state: draft.state,
@@ -70404,6 +72113,8 @@ function privateLessonDraftActionResult2(draft, extra = {}) {
70404
72113
  hold_event_digest: draft.hold_event_digest,
70405
72114
  hold_receipt_digest: draft.hold_receipt_digest,
70406
72115
  hold_reported_at: draft.hold_reported_at,
72116
+ ...safetyRecheckField(draft),
72117
+ ...privateLessonRecoveryFields(draft, destination),
70407
72118
  retained_locally: draft.state !== "submitted",
70408
72119
  next_action: privateLessonDraftNextAction(draft),
70409
72120
  ...extra
@@ -70949,6 +72660,9 @@ async function callRemembrance(definition, rawArguments, options) {
70949
72660
  throw new McpPublicError(configurationError);
70950
72661
  }
70951
72662
  const apiKey = credential.apiKey;
72663
+ if (definition.name === "repair_review_draft") {
72664
+ headers["Idempotency-Key"] = String(parsed.request_id);
72665
+ }
70952
72666
  if (apiKey) {
70953
72667
  headers["x-remembrance-api-key"] = apiKey;
70954
72668
  }
@@ -70992,6 +72706,7 @@ async function callRemembrance(definition, rawArguments, options) {
70992
72706
  let response;
70993
72707
  let body;
70994
72708
  let redirectRejected = false;
72709
+ let reviewWorkflowStatus = 0;
70995
72710
  try {
70996
72711
  const execute = async () => {
70997
72712
  const nextResponse = await transport.request(
@@ -71004,6 +72719,7 @@ async function callRemembrance(definition, rawArguments, options) {
71004
72719
  signal: controller.signal
71005
72720
  }
71006
72721
  );
72722
+ reviewWorkflowStatus = nextResponse.status;
71007
72723
  if (options.redirect === "manual" && (nextResponse.redirected || nextResponse.status >= 300 && nextResponse.status < 400)) {
71008
72724
  void nextResponse.body?.cancel().catch(() => void 0);
71009
72725
  return {
@@ -71018,7 +72734,13 @@ async function callRemembrance(definition, rawArguments, options) {
71018
72734
  let nextBody;
71019
72735
  try {
71020
72736
  nextBody = await readBoundedResponseJson(nextResponse);
72737
+ if (nextResponse.ok && ["get_review_comparison", "repair_review_draft"].includes(definition.name) && !reviewWorkflowResponseBound(definition.name, nextBody, parsed)) {
72738
+ throw new McpPublicError("The review response did not match this request.");
72739
+ }
71021
72740
  } catch {
72741
+ if (["get_review_comparison", "repair_review_draft"].includes(definition.name)) {
72742
+ throw new McpPublicError("The review response is unreadable or unbound.");
72743
+ }
71022
72744
  if (controller.signal.aborted) {
71023
72745
  throw new DOMException("Request timed out", "AbortError");
71024
72746
  }
@@ -71057,6 +72779,26 @@ async function callRemembrance(definition, rawArguments, options) {
71057
72779
  }
71058
72780
  }
71059
72781
  } catch (error) {
72782
+ if (definition.name === "repair_review_draft") {
72783
+ return {
72784
+ ok: false,
72785
+ status: reviewWorkflowStatus,
72786
+ error: "The review repair outcome is unknown. Reconcile by repeating only this exact request with the same request_id; do not create another replacement.",
72787
+ body: {
72788
+ code: "review_repair_outcome_unknown",
72789
+ delivery: "unknown",
72790
+ request_id: parsed.request_id,
72791
+ next_action: "Keep the original and repeat only the identical request_id, capture and snapshot to recover the committed receipt. Do not change input or use a new ID while this outcome is unknown."
72792
+ }
72793
+ };
72794
+ }
72795
+ if (definition.name === "get_review_comparison") {
72796
+ return {
72797
+ ok: false,
72798
+ status: reviewWorkflowStatus,
72799
+ body: { code: "review_comparison_unreadable", error: "No valid comparison was returned for this exact review job. Keep it unchanged and read its current references again." }
72800
+ };
72801
+ }
71060
72802
  return {
71061
72803
  ok: false,
71062
72804
  status: 0,
@@ -71065,6 +72807,25 @@ async function callRemembrance(definition, rawArguments, options) {
71065
72807
  } finally {
71066
72808
  clearTimeout(timeout);
71067
72809
  }
72810
+ if (["get_review_comparison", "repair_review_draft"].includes(definition.name) && (!response.ok || redirectRejected)) {
72811
+ const failure = remembranceMcpToolFailure({
72812
+ ok: false,
72813
+ status: response.status,
72814
+ body,
72815
+ retry_after: response.headers.get("retry-after"),
72816
+ redirect_rejected: redirectRejected
72817
+ }, definition.name);
72818
+ body = {
72819
+ error: failure?.message ?? "The review operation failed.",
72820
+ code: failure?.code ?? "review_workflow_failed",
72821
+ retryable: failure?.retryable ?? false,
72822
+ delivery: failure?.delivery ?? "unknown",
72823
+ ...definition.name === "repair_review_draft" ? {
72824
+ request_id: parsed.request_id,
72825
+ next_action: "If delivery is unknown, repeat only the identical request_id, capture and snapshot to reconcile it. Never create a new replacement for an unresolved write."
72826
+ } : {}
72827
+ };
72828
+ }
71068
72829
  const verifiedBody = definition.name === "get_value_proof" && response.ok ? await verifySignedValueProofWithKeyRefresh(
71069
72830
  body,
71070
72831
  (forceRefresh) => fetchValueProofKeySet(forceRefresh, access, transport)
@@ -71452,8 +73213,12 @@ function formatConnectionDoctorReport(report) {
71452
73213
  lines2.push(`[${check.status.toUpperCase()}] ${check.id}: ${check.summary}`);
71453
73214
  if (check.remediation) {
71454
73215
  lines2.push(` Fix: ${check.remediation.action}`);
71455
- if (check.remediation.command) {
71456
- lines2.push(` Command: ${check.remediation.command}`);
73216
+ const command = check.remediation.command;
73217
+ if (command) {
73218
+ lines2.push(
73219
+ command.includes("\n") ? ` Command:
73220
+ ${command.replace(/^/gm, " ")}` : ` Command: ${command}`
73221
+ );
71457
73222
  }
71458
73223
  }
71459
73224
  }
@@ -71583,7 +73348,7 @@ function endpointFor(definition, payload) {
71583
73348
  const query2 = privateLessonPolicyQuery(payload);
71584
73349
  return query2 ? `${endpoint}?${query2}` : endpoint;
71585
73350
  }
71586
- const queryKeys = definition.name === "list_skills" ? ["q", "slug", "cursor", "limit"] : ["query_id", "result_id"];
73351
+ const queryKeys = definition.name === "list_skills" ? ["q", "slug", "cursor", "limit"] : definition.name === "get_review_comparison" ? ["job_id", "review_provenance"] : ["query_id", "result_id"];
71587
73352
  for (const key of queryKeys) {
71588
73353
  const value = payload[key];
71589
73354
  if (typeof value === "string" && value || typeof value === "number" && Number.isFinite(value)) {