@c4a/context-cli 0.7.95 → 0.7.96

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/cli.js CHANGED
@@ -70764,7 +70764,7 @@ async function registeredArticleSourceReader(projectRoot) {
70764
70764
  const managed = kind === "note" || kind === "sessions";
70765
70765
  const root = await realpath5(resolve19(workspace, managed ? dirname12(entry.materializedAt) : entry.materializedAt)).catch((error) => {
70766
70766
  if (kind === "repo")
70767
- throw new SourceReadError("The registered source checkout is not accessible. Restore the source before checking citations.", "context source recovery-plan --format json");
70767
+ throw new SourceReadError(`The registered source checkout of ${sourceRef} is not accessible. Restore the source before checking citations.`, "context source recovery-plan --format json");
70768
70768
  throw error;
70769
70769
  });
70770
70770
  inside(workspace, root);
@@ -77056,12 +77056,13 @@ function formatPackageBuildSummary(pkg) {
77056
77056
  ...formatPackageChangeLines("removed", pkg.changes.removed)
77057
77057
  ];
77058
77058
  }
77059
- function formatProjectBuildResult(result, format2 = "text", verbose = false) {
77059
+ function formatProjectBuildResult(result, format2 = "text", verbose = false, extra = {}) {
77060
77060
  if (format2 === "json") {
77061
77061
  if (verbose)
77062
- return `${JSON.stringify(result, null, 2)}
77062
+ return `${JSON.stringify({ ...result, ...extra }, null, 2)}
77063
77063
  `;
77064
77064
  return `${JSON.stringify({
77065
+ ...extra,
77065
77066
  agent_hints: result.agent_hints,
77066
77067
  packages: result.packages.map((pkg) => ({
77067
77068
  name: pkg.name,
@@ -78131,8 +78132,9 @@ import { execFile as execFile5 } from "node:child_process";
78131
78132
  import { promisify as promisify4 } from "node:util";
78132
78133
  import { mkdir as mkdir13, mkdtemp as mkdtemp2, rm as rm7, writeFile as writeFile8 } from "node:fs/promises";
78133
78134
  import { join as join21 } from "node:path";
78134
- async function hunks(root, before, after) {
78135
- const parent = join21(root, ".tmp/context-runtime/reference-diff");
78135
+ import { tmpdir } from "node:os";
78136
+ async function hunks(_root, before, after) {
78137
+ const parent = join21(tmpdir(), "context-reference-diff");
78136
78138
  await mkdir13(parent, { recursive: true });
78137
78139
  const directory = await mkdtemp2(join21(parent, "compare-"));
78138
78140
  try {
@@ -78367,7 +78369,7 @@ function articleReferenceHistoryReader(root, previous2 = []) {
78367
78369
  return baseline === undefined ? undefined : { region: baseline };
78368
78370
  };
78369
78371
  }
78370
- var hashRegion = (text5) => `sha256:${createHash13("sha256").update(text5, "utf8").digest("hex")}`, referenceEvidenceKey = (reference2) => indexerProtocolDigest(reference2), exec3;
78372
+ var LOCAL_SOURCE_REASONS, hashRegion = (text5) => `sha256:${createHash13("sha256").update(text5, "utf8").digest("hex")}`, referenceEvidenceKey = (reference2) => indexerProtocolDigest(reference2), exec3;
78371
78373
  var init_articleReferenceObservation = __esm(() => {
78372
78374
  init_src2();
78373
78375
  init_articleRegionBaselines();
@@ -78375,6 +78377,10 @@ var init_articleReferenceObservation = __esm(() => {
78375
78377
  init_articleSourceReader();
78376
78378
  init_gitObjectReader();
78377
78379
  init_referenceRangeMap();
78380
+ LOCAL_SOURCE_REASONS = {
78381
+ "source-content-missing": "The cited file contents are not downloaded in the source checkout.",
78382
+ "source-history-missing": "The registered commit is not in the source checkout."
78383
+ };
78378
78384
  exec3 = promisify5(execFile6);
78379
78385
  });
78380
78386
 
@@ -80419,6 +80425,7 @@ var init_productionArticleTarget = __esm(() => {
80419
80425
  var exports_productionFeedback = {};
80420
80426
  __export(exports_productionFeedback, {
80421
80427
  withProductionFeedback: () => withProductionFeedback,
80428
+ SubmissionInputErrors: () => SubmissionInputErrors,
80422
80429
  SubmissionInputError: () => SubmissionInputError
80423
80430
  });
80424
80431
  async function withProductionFeedback(input, run) {
@@ -80447,7 +80454,7 @@ async function withProductionFeedback(input, run) {
80447
80454
  throw new ContextError(existing?.code ?? (schemaError2 || syntaxError || inputError ? ExitCode.UserError : ExitCode.WorkspaceStateError), error instanceof Error ? error.message : String(error), detail);
80448
80455
  }
80449
80456
  }
80450
- var import_yaml19, SubmissionInputError;
80457
+ var import_yaml19, SubmissionInputError, SubmissionInputErrors;
80451
80458
  var init_productionFeedback = __esm(() => {
80452
80459
  init_zod();
80453
80460
  init_esm();
@@ -80464,6 +80471,13 @@ var init_productionFeedback = __esm(() => {
80464
80471
  this.reason = reason;
80465
80472
  }
80466
80473
  };
80474
+ SubmissionInputErrors = class SubmissionInputErrors extends SubmissionInputError {
80475
+ errors;
80476
+ constructor(errors4) {
80477
+ super(`${errors4.length} problems: ${errors4.map((error, index2) => `(${index2 + 1}) ${error.message}`).join(" ")}`, errors4[0]?.path ?? [], errors4[0]?.reason);
80478
+ this.errors = errors4;
80479
+ }
80480
+ };
80467
80481
  });
80468
80482
 
80469
80483
  // src/project/productionStage.ts
@@ -82833,6 +82847,26 @@ async function migrateCheckpoint(root, original, value) {
82833
82847
  });
82834
82848
  } catch {}
82835
82849
  }
82850
+ async function versionMergedTo(root, version3) {
82851
+ const git2 = (args) => exec5("git", args, { cwd: root, timeout: 1e4, maxBuffer: 16 * 1024 * 1024 }).then((value) => value.stdout.trim(), () => {
82852
+ return;
82853
+ });
82854
+ const prefix = await git2(["rev-parse", "--show-prefix"]);
82855
+ if (prefix === undefined)
82856
+ return;
82857
+ const head = await git2(["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]);
82858
+ for (const ref2 of [...head ? [head] : [], "origin/main", "origin/master"]) {
82859
+ const text7 = await git2(["show", `${ref2}:${prefix}changelog.yaml`]);
82860
+ if (text7 === undefined)
82861
+ continue;
82862
+ try {
82863
+ if (ledgerSchema.parse(import_yaml28.parse(text7)).entries.some((entry) => entry.version === version3))
82864
+ return ref2;
82865
+ } catch {}
82866
+ return;
82867
+ }
82868
+ return;
82869
+ }
82836
82870
  async function inspectWorkspaceVersion(root, baseRef) {
82837
82871
  const snapshot = await observeWorkspaceContent(root);
82838
82872
  const { files } = snapshot;
@@ -82858,11 +82892,13 @@ async function inspectWorkspaceVersion(root, baseRef) {
82858
82892
  const recorded = entries[0]?.version === version3;
82859
82893
  const matches = checkpoint?.version === version3 && checkpoint.digest === digest3;
82860
82894
  const changed = checkpoint?.version === version3 ? !matches : comparison.added.length + comparison.updated.length + comparison.removed.length > 0 || !recorded;
82895
+ const mergedTo = recorded && !comparison.tagged ? await versionMergedTo(root, version3) : undefined;
82861
82896
  return {
82862
82897
  version: version3,
82863
82898
  previous_version: version3,
82864
82899
  changed,
82865
- reusable_version: recorded && !comparison.tagged ? version3 : null,
82900
+ reusable_version: recorded && !comparison.tagged && !mergedTo ? version3 : null,
82901
+ ...mergedTo ? { merged_to: mergedTo } : {},
82866
82902
  current: recorded && (matches || checkpoint?.version !== version3 && (comparison.base_commit === null || !changed)),
82867
82903
  expected_digest: hash2({ files, version: version3, entries, base: comparison.base_commit }),
82868
82904
  ...comparison,
@@ -82919,7 +82955,7 @@ async function recordWorkspaceVersion(root, value) {
82919
82955
  const a = previous2.split(".").map(Number), b = input.version.split(".").map(Number);
82920
82956
  const amend = status.reusable_version === input.version;
82921
82957
  if (!amend && !(b[0] > a[0] || b[0] === a[0] && (b[1] > a[1] || b[1] === a[1] && b[2] > a[2])))
82922
- throw new TypeError("The new SemVer must be greater than the previous workspace version; only an untagged current entry may be amended after checking the publication target.");
82958
+ throw new TypeError("The new SemVer must be greater than the previous workspace version; only an untagged current entry that is not yet on the remote default branch may be amended.");
82923
82959
  let actor = input.actor ?? (amend ? previousEntries[0]?.actor : undefined);
82924
82960
  if (!actor) {
82925
82961
  try {
@@ -85644,6 +85680,38 @@ var init_runtimeEvents = __esm(() => {
85644
85680
  });
85645
85681
 
85646
85682
  // src/project/approvedKnowledgeDependencyWarnings.ts
85683
+ async function classifyCitation(sectionId, reference2, observe, repoImpact) {
85684
+ const where = `${sectionId}: ${reference2.source_ref}/${reference2.locator.path}`;
85685
+ try {
85686
+ if (reference2.source_ref.startsWith("repo-content:")) {
85687
+ const impact = await (await repoImpact)(reference2);
85688
+ if (impact.state === "unchanged")
85689
+ return { kind: "current" };
85690
+ if (impact.state === "moved")
85691
+ return { kind: "moved", text: `${sectionId}: ${reference2.source_ref}/${impact.current_path ?? reference2.locator.path}` };
85692
+ return { kind: "changed", text: `${where} (changed)` };
85693
+ }
85694
+ const result = await observe(reference2);
85695
+ if (result.state === "current")
85696
+ return { kind: "current" };
85697
+ if (result.state === "moved") {
85698
+ const locator = result.reference.locator;
85699
+ return { kind: "moved", text: `${sectionId}: ${reference2.source_ref}/${locator.path} L${locator.start_line}–L${locator.end_line}` };
85700
+ }
85701
+ if (result.state === "unavailable" && (result.reason ?? "") in LOCAL_SOURCE_REASONS) {
85702
+ return { kind: "unchecked", reason: `${LOCAL_SOURCE_REASONS[result.reason]} (${reference2.source_ref}, ${result.reason})` };
85703
+ }
85704
+ return {
85705
+ kind: "changed",
85706
+ state: { section_id: sectionId, state: result.state, ...result.reason ? { reason: result.reason } : {} },
85707
+ text: `${where} L${reference2.locator.start_line}–L${reference2.locator.end_line} (${result.state}${result.reason ? `, ${result.reason}` : ""})`
85708
+ };
85709
+ } catch (error) {
85710
+ if (!(error instanceof SourceReadError))
85711
+ throw error;
85712
+ return { kind: "unchecked", reason: error.message };
85713
+ }
85714
+ }
85647
85715
  async function approvedKnowledgeDependencyWarnings(projectRoot, structureOverride) {
85648
85716
  const articles = approvedKnowledgeSnapshotsFromStructure(structureOverride ?? (await readKnowledgeStructure(projectRoot)).parsed);
85649
85717
  if (!articles.some((article) => article.sections.some((section) => section.references.length)))
@@ -85653,46 +85721,28 @@ async function approvedKnowledgeDependencyWarnings(projectRoot, structureOverrid
85653
85721
  const issues = [];
85654
85722
  let repoImpact;
85655
85723
  let pending;
85724
+ const unreadable = new Map;
85656
85725
  for (const article of articles) {
85657
85726
  const changed = [];
85658
85727
  const moved = [];
85659
85728
  const referenceStates = [];
85660
85729
  for (const section of article.sections) {
85661
85730
  for (const reference2 of section.references) {
85662
- try {
85663
- if (reference2.source_ref.startsWith("repo-content:")) {
85664
- repoImpact ??= repoContentImpactReader(projectRoot);
85665
- const impact = await (await repoImpact)(reference2);
85666
- if (impact.state === "unchanged")
85667
- continue;
85668
- if (impact.state === "moved") {
85669
- moved.push(`${section.id}: ${reference2.source_ref}/${impact.current_path ?? reference2.locator.path}`);
85670
- continue;
85671
- }
85672
- changed.push(section.id);
85673
- break;
85674
- }
85675
- const result = await observe(reference2);
85676
- if (result.state === "current")
85677
- continue;
85678
- if (result.state === "moved") {
85679
- const locator = result.reference.locator;
85680
- moved.push(`${section.id}: ${reference2.source_ref}/${locator.path} L${locator.start_line}–L${locator.end_line}`);
85681
- continue;
85682
- }
85683
- referenceStates.push({ section_id: section.id, state: result.state, ...result.reason ? { reason: result.reason } : {} });
85684
- changed.push(section.id);
85685
- break;
85686
- } catch (error) {
85687
- if (!(error instanceof SourceReadError))
85688
- throw error;
85689
- issues.push({
85690
- severity: "warning",
85691
- code: "source-read-failed",
85692
- path: article.path,
85693
- source_keys: [reference2.source_ref],
85694
- message: `${reference2.source_ref}/${reference2.locator.path}: ${error.message} No citation state was determined. Run context source recovery-plan --format json, then retry verification.`
85695
- });
85731
+ if (reference2.source_ref.startsWith("repo-content:"))
85732
+ repoImpact ??= repoContentImpactReader(projectRoot);
85733
+ const citation = await classifyCitation(section.id, reference2, observe, repoImpact);
85734
+ if (citation.kind === "moved")
85735
+ moved.push(citation.text);
85736
+ else if (citation.kind === "changed") {
85737
+ changed.push(citation.text);
85738
+ if (citation.state)
85739
+ referenceStates.push(citation.state);
85740
+ } else if (citation.kind === "unchecked") {
85741
+ const entry = unreadable.get(reference2.source_ref) ?? { pages: [], citations: 0, reason: citation.reason };
85742
+ entry.citations++;
85743
+ if (!entry.pages.includes(article.path))
85744
+ entry.pages.push(article.path);
85745
+ unreadable.set(reference2.source_ref, entry);
85696
85746
  }
85697
85747
  }
85698
85748
  }
@@ -85706,7 +85756,7 @@ async function approvedKnowledgeDependencyWarnings(projectRoot, structureOverrid
85706
85756
  code: "approved-source-region-changed",
85707
85757
  path: article.path,
85708
85758
  ...referenceStates.length ? { reference_states: referenceStates } : {},
85709
- message: `Source regions changed or are unavailable for fragments: ${changed.join(", ")}.${update || " Inspect current sources and revise this article;"} Verification does not rewrite approved references.`
85759
+ message: `Cited source regions changed or are unavailable: ${changed.join("; ")}.${update || " Inspect current sources and revise this article;"} Verification does not rewrite approved references.`
85710
85760
  });
85711
85761
  if (moved.length)
85712
85762
  issues.push({
@@ -85716,6 +85766,16 @@ async function approvedKnowledgeDependencyWarnings(projectRoot, structureOverrid
85716
85766
  message: `Cited regions are unchanged but their location or surrounding source changed: ${moved.join("; ")}.${update || " Check locators during the source update;"} Do not rewrite unaffected prose.`
85717
85767
  });
85718
85768
  }
85769
+ for (const [source2, entry] of unreadable) {
85770
+ const shown = entry.pages.slice(0, 5).join(", ") + (entry.pages.length > 5 ? `, and ${entry.pages.length - 5} more` : "");
85771
+ issues.push({
85772
+ severity: "warning",
85773
+ code: "source-read-failed",
85774
+ path: entry.pages[0],
85775
+ source_keys: [source2],
85776
+ message: `${entry.reason} ${entry.citations} citation(s) in ${entry.pages.length} page(s) were not checked (${shown}). ` + "This is not a citation change. Restore a missing checkout with context source recovery-plan --format json; " + "context update --pending downloads missing commits and contents. Then retry verification."
85777
+ });
85778
+ }
85719
85779
  return issues;
85720
85780
  }
85721
85781
  var init_approvedKnowledgeDependencyWarnings = __esm(() => {
@@ -95819,7 +95879,13 @@ async function runProjectBuildCommand(input) {
95819
95879
  const deliveryHint = runtimeEventPendingAgentHint(await flushQueuedContextRuntimeEvents(result.projectRoot));
95820
95880
  if (deliveryHint !== undefined)
95821
95881
  result.agent_hints.push(deliveryHint);
95822
- process.stdout.write(formatProjectBuildResult(result, input.format ?? "text", input.verbose === true));
95882
+ let extra = {};
95883
+ if (input.format === "json") {
95884
+ try {
95885
+ extra = { workflow: (await (await Promise.resolve().then(() => (init_status(), exports_status))).collectProjectStatus(found.projectRoot, input.execution ?? {})).workflow };
95886
+ } catch {}
95887
+ }
95888
+ process.stdout.write(formatProjectBuildResult(result, input.format ?? "text", input.verbose === true, extra));
95823
95889
  return true;
95824
95890
  }
95825
95891
  var import_yaml44, PACKAGE_FINGERPRINT_ROOT, PACKAGE_BUILDER_PROTOCOL_VERSION = "v23-sibling-site-output";
@@ -97143,6 +97209,41 @@ var init_approvedRevisionEdits = __esm(() => {
97143
97209
  });
97144
97210
 
97145
97211
  // src/project/approvedRevisionReferences.ts
97212
+ async function resolveSubmittedReference(context, id3, at2, reference2) {
97213
+ if (!context.inScope(reference2.source_ref))
97214
+ throw new SubmissionInputError(`Fragment ${id3} cites ${reference2.source_ref}, which is outside this revision; allowed sources: ${context.sourceRefs.join(", ")}. ` + "To cite new independent evidence, register it as a source, associate it with the selected requirement in src/indexers.yaml, then run context task adjust for this revision.", [...at2, "source_ref"], "source-outside-revision");
97215
+ const submitted = reference2.locator;
97216
+ const previous2 = context.previous.find((section) => section.id === id3)?.references ?? [];
97217
+ const kept = "start_line" in submitted ? previous2.find((old) => old.source_ref === reference2.source_ref && old.locator.path === submitted.path && old.locator.start_line === submitted.start_line && old.locator.end_line === submitted.end_line) : undefined;
97218
+ if (kept) {
97219
+ const observed = await relocateUnchangedReference(context.projectRoot, context.readSource, kept);
97220
+ if (observed.state === "current" || observed.state === "moved")
97221
+ return observed.reference;
97222
+ throw new SubmissionInputError(`Fragment ${id3}: ${reference2.source_ref} ${kept.locator.path}:${kept.locator.start_line}-${kept.locator.end_line} ` + `repeats an earlier citation, so it keeps that evidence, which is ${observed.state} in the current source. ` + "To keep the earlier evidence, cite its current position. To cite the text now at these lines (it may be the correct new content), use a quote or heading locator.", [...at2, "locator"], "kept-reference-unresolved");
97223
+ }
97224
+ const text8 = await context.readSource(reference2.source_ref, reference2.locator.path, true);
97225
+ let locator;
97226
+ try {
97227
+ locator = resolveSubmittedSourceLocator(reference2.locator, text8);
97228
+ } catch (error) {
97229
+ if (error instanceof SubmissionInputError)
97230
+ throw new SubmissionInputError(`Fragment ${id3}: ${error.message}`, [...at2, "locator"]);
97231
+ throw error;
97232
+ }
97233
+ let resolved;
97234
+ try {
97235
+ resolved = createArticleSourceReference(reference2.source_ref, locator, text8);
97236
+ } catch (error) {
97237
+ if (!(error instanceof RangeError))
97238
+ throw error;
97239
+ throw new SubmissionInputError(`Fragment ${id3}: ${reference2.source_ref} ${locator.path}:${locator.start_line}-${locator.end_line} ` + `is outside the file, which has ${text8.replace(/\r\n/gu, `
97240
+ `).split(`
97241
+ `).length} lines. Cite existing lines, or use a quote or heading locator.`, [...at2, "locator"], "locator-out-of-range");
97242
+ }
97243
+ if (context.remember)
97244
+ rememberArticleRegion(context.projectRoot, resolved, text8);
97245
+ return resolved;
97246
+ }
97146
97247
  async function prepareRevisionReferences(input) {
97147
97248
  const edits = new Map(input.edits?.map((edit) => [edit.section_id, edit]));
97148
97249
  if (edits.size !== (input.edits?.length ?? 0))
@@ -97153,63 +97254,116 @@ async function prepareRevisionReferences(input) {
97153
97254
  }
97154
97255
  let read;
97155
97256
  const inScope = (source2) => input.sourceRefs.some((scope2) => repoContentScopeMatches(scope2, source2));
97156
- const readSource = async (source2, path2) => {
97157
- if (!inScope(source2))
97158
- throw new TypeError(`Source is outside this revision: ${source2}`);
97159
- read ??= await registeredArticleSourceReader(input.projectRoot);
97160
- return read(source2, path2, true);
97257
+ const context = {
97258
+ projectRoot: input.projectRoot,
97259
+ remember: input.remember !== false,
97260
+ previous: input.previous,
97261
+ sourceRefs: input.sourceRefs,
97262
+ inScope,
97263
+ readSource: Object.assign(async (source2, path2) => {
97264
+ if (!inScope(source2))
97265
+ throw new TypeError(`Source is outside this revision: ${source2}`);
97266
+ read ??= await registeredArticleSourceReader(input.projectRoot);
97267
+ return read(source2, path2, true);
97268
+ }, { incomplete: async (source2) => {
97269
+ read ??= await registeredArticleSourceReader(input.projectRoot);
97270
+ return await read.incomplete?.(source2) ?? false;
97271
+ } })
97161
97272
  };
97162
97273
  const result = [];
97274
+ const problems = [];
97163
97275
  for (const id3 of input.sectionIds) {
97164
97276
  const edit = edits.get(id3);
97165
97277
  if (edit?.references !== undefined) {
97166
97278
  const at2 = ["sections", input.edits.indexOf(edit), "references"];
97167
- const previous2 = input.previous.find((section) => section.id === id3)?.references ?? [];
97168
97279
  const references2 = [];
97169
97280
  for (const [index3, reference2] of edit.references.entries()) {
97170
- if (!inScope(reference2.source_ref))
97171
- throw new SubmissionInputError(`Fragment ${id3} cites ${reference2.source_ref}, which is outside this revision; allowed sources: ${input.sourceRefs.join(", ")}. ` + "To cite new independent evidence, register it as a source, associate it with the selected requirement in src/indexers.yaml, then run context task adjust for this revision.", [...at2, index3, "source_ref"], "source-outside-revision");
97172
- const submitted = reference2.locator;
97173
- const kept = "start_line" in submitted ? previous2.find((old) => old.source_ref === reference2.source_ref && old.locator.path === submitted.path && old.locator.start_line === submitted.start_line && old.locator.end_line === submitted.end_line) : undefined;
97174
- if (kept) {
97175
- const observed = await relocateUnchangedReference(input.projectRoot, readSource, kept);
97176
- if (observed.state === "current" || observed.state === "moved") {
97177
- references2.push(observed.reference);
97178
- continue;
97179
- }
97180
- throw new SubmissionInputError(`Fragment ${id3}: ${reference2.source_ref} ${kept.locator.path}:${kept.locator.start_line}-${kept.locator.end_line} ` + `repeats an earlier citation, so it keeps that evidence, which is ${observed.state} in the current source. ` + "To keep the earlier evidence, cite its current position. To cite the text now at these lines (it may be the correct new content), use a quote or heading locator.", [...at2, index3, "locator"], "kept-reference-unresolved");
97181
- }
97182
- const text8 = await readSource(reference2.source_ref, reference2.locator.path);
97183
- let locator;
97184
97281
  try {
97185
- locator = resolveSubmittedSourceLocator(reference2.locator, text8);
97282
+ references2.push(await resolveSubmittedReference(context, id3, [...at2, index3], reference2));
97186
97283
  } catch (error) {
97187
- if (error instanceof SubmissionInputError)
97188
- throw new SubmissionInputError(`Fragment ${id3}: ${error.message}`, [...at2, index3, "locator"]);
97189
- throw error;
97284
+ if (error instanceof SourceReadError || error instanceof SourceUnavailableError) {
97285
+ problems.push(new SubmissionInputError(`Fragment ${id3}: ${reference2.source_ref} ${reference2.locator.path}: ${error.message}`, [...at2, index3, "source_ref"], String(error.detail?.reason_code ?? "source-unavailable")));
97286
+ } else if (error instanceof SubmissionInputError)
97287
+ problems.push(error);
97288
+ else
97289
+ throw error;
97190
97290
  }
97191
- const resolved = createArticleSourceReference(reference2.source_ref, locator, text8);
97192
- if (input.remember !== false)
97193
- rememberArticleRegion(input.projectRoot, resolved, text8);
97194
- references2.push(resolved);
97195
97291
  }
97196
97292
  try {
97197
97293
  result.push({ id: id3, references: articleFragmentReferences(references2) });
97198
97294
  } catch (error) {
97199
97295
  if (error instanceof ZodError)
97200
- throw new SubmissionInputError(`Fragment ${id3}: ${error.issues.map((issue) => issue.message).join("; ")}`, at2);
97201
- throw error;
97296
+ problems.push(new SubmissionInputError(`Fragment ${id3}: ${error.issues.map((issue) => issue.message).join("; ")}`, at2));
97297
+ else
97298
+ throw error;
97202
97299
  }
97203
97300
  continue;
97204
97301
  }
97205
97302
  const references = [];
97206
- for (const reference2 of input.previous.find((section) => section.id === id3)?.references ?? []) {
97207
- references.push((await relocateUnchangedReference(input.projectRoot, readSource, reference2)).reference);
97303
+ const retained = input.previous.find((section) => section.id === id3)?.references ?? [];
97304
+ for (const [index3, reference2] of retained.entries()) {
97305
+ references.push(await retainReference(input, context, id3, ["fragments", id3, "references", index3], reference2, problems));
97208
97306
  }
97209
97307
  result.push({ id: id3, references });
97210
97308
  }
97309
+ if (problems.length === 1)
97310
+ throw problems[0];
97311
+ if (problems.length)
97312
+ throw new SubmissionInputErrors(problems);
97211
97313
  return result;
97212
97314
  }
97315
+ async function retainReference(input, context, id3, at2, reference2, problems) {
97316
+ const changed = input.changedBodies?.has(id3) === true;
97317
+ const where = `${reference2.source_ref} ${reference2.locator.path}:${reference2.locator.start_line}-${reference2.locator.end_line}`;
97318
+ let observed;
97319
+ try {
97320
+ observed = await relocateUnchangedReference(context.projectRoot, context.readSource, reference2);
97321
+ } catch (error) {
97322
+ if (!(error instanceof SourceReadError))
97323
+ throw error;
97324
+ if (changed)
97325
+ problems.push(new SubmissionInputError(`Fragment ${id3}: the text changed, but ${where} cannot be checked: ${error.message}`, at2, "reference-unverifiable"));
97326
+ return reference2;
97327
+ }
97328
+ if (observed.state === "current" || observed.state === "moved")
97329
+ return observed.reference;
97330
+ if (observed.state === "unavailable" && (observed.reason ?? "") in LOCAL_SOURCE_REASONS) {
97331
+ if (changed)
97332
+ problems.push(new SubmissionInputError(`Fragment ${id3}: the text changed, but ${where} cannot be checked on this machine (${observed.reason}). Make the source available, then submit again.`, at2, "reference-unverifiable"));
97333
+ return reference2;
97334
+ }
97335
+ if (citesScope(input.processedScopes ?? [], reference2.source_ref)) {
97336
+ const hint = await input.suggest?.(reference2).catch(() => {
97337
+ return;
97338
+ });
97339
+ problems.push(new SubmissionInputError(`Fragment ${id3}: ${where} is ${observed.state}${observed.reason ? ` (${observed.reason})` : ""} in the source version this revision processes. ` + `Rewrite the paragraph, cite its current text${hint ? ` (${hint})` : ""}, or remove the citation.`, at2, "processed-reference-stale"));
97340
+ return reference2;
97341
+ }
97342
+ input.onReminder?.({
97343
+ section_id: id3,
97344
+ state: observed.state,
97345
+ ...observed.reason ? { reason: observed.reason } : {},
97346
+ source_ref: reference2.source_ref,
97347
+ locator: reference2.locator
97348
+ });
97349
+ return reference2;
97350
+ }
97351
+ async function suggestedCitation(projectRoot, reference2, sections) {
97352
+ const history = await articleReferenceHistoryReader(projectRoot, readProcessedScopes((await readKnowledgeStructure(projectRoot)).parsed))(reference2);
97353
+ if (!history?.text)
97354
+ return;
97355
+ const current3 = await (await registeredArticleSourceReader(projectRoot))(reference2.source_ref, reference2.locator.path, true);
97356
+ const cited = sections.flatMap((section) => section.references.map((item) => ({
97357
+ source_ref: item.source_ref,
97358
+ path: item.locator.path,
97359
+ start_line: item.locator.start_line,
97360
+ end_line: item.locator.end_line
97361
+ })));
97362
+ const suggested = await suggestedRange(projectRoot, reference2, history.text, current3, cited);
97363
+ if (!suggested)
97364
+ return;
97365
+ return "quote" in suggested.locator ? `the old text now maps to lines ${suggested.start_line}-${suggested.end_line}; cite them with a quote locator` : `the old text now maps to lines ${suggested.start_line}-${suggested.end_line}`;
97366
+ }
97213
97367
  function removedCitations(previous2, next) {
97214
97368
  const removed = [];
97215
97369
  for (const section of previous2) {
@@ -97228,7 +97382,13 @@ function removedCitations(previous2, next) {
97228
97382
  }
97229
97383
  return removed;
97230
97384
  }
97231
- var REMOVED_CITATIONS_NOTE = "These earlier citations are no longer in their sections. If you meant to replace or remove them, nothing needs doing; otherwise repeat each with its earlier lines to keep that evidence.";
97385
+ function citationNotes(removed, reminders) {
97386
+ return {
97387
+ ...removed.length ? { removed_citations: [...removed], removed_citations_note: REMOVED_CITATIONS_NOTE } : {},
97388
+ ...reminders.length ? { reference_warnings: [...reminders], reference_warning_instruction: REFERENCE_REMINDER_NOTE } : {}
97389
+ };
97390
+ }
97391
+ var citesScope = (scopes, ref2) => scopes.some((scope2) => repoContentScopeMatches(scope2, ref2) || ref2.startsWith(`${scope2}#`) || ref2.startsWith(`${scope2}/`)), REFERENCE_REMINDER_NOTE = "These paragraphs keep citations their sources no longer confirm. The sources are outside what this revision processes, so the citations were kept; check them in a source update or a separate revision.", REMOVED_CITATIONS_NOTE = "These earlier citations are no longer in their sections. If you meant to replace or remove them, nothing needs doing; otherwise repeat each with its earlier lines to keep that evidence.";
97232
97392
  var init_approvedRevisionReferences = __esm(() => {
97233
97393
  init_zod();
97234
97394
  init_submittedSourceLocator();
@@ -97237,6 +97397,10 @@ var init_approvedRevisionReferences = __esm(() => {
97237
97397
  init_articleRegionBaselines();
97238
97398
  init_settledReferenceRelocation();
97239
97399
  init_articleSourceReader();
97400
+ init_gitObjectReader();
97401
+ init_articleReferenceObservation();
97402
+ init_packageBuildInventory();
97403
+ init_src2();
97240
97404
  });
97241
97405
 
97242
97406
  // src/project/approvedPageMove.ts
@@ -97589,13 +97753,19 @@ async function composeRevisionCandidate(projectRoot, request, input, options) {
97589
97753
  throw new TypeError("Revision section identities must be unique");
97590
97754
  }
97591
97755
  const title = exports_external.string().trim().min(1).parse(metadata.title);
97756
+ const before = new Map(approvedContextSectionsInMarkdown(request.target.markdown).map((section) => [section.id, section.readerVisibleBody]));
97757
+ const reminders = [];
97592
97758
  const references = await prepareRevisionReferences({
97593
97759
  projectRoot,
97594
97760
  sourceRefs: request.target.source_refs,
97595
97761
  previous: request.target.sections,
97596
97762
  sectionIds: sections.map((section) => section.id),
97597
97763
  edits: input.sections,
97598
- remember: options.remember
97764
+ remember: options.remember,
97765
+ processedScopes: (request.processed_scopes ?? []).map((scope2) => scope2.source_ref),
97766
+ changedBodies: new Set(sections.filter((section) => before.get(section.id) !== section.readerVisibleBody).map((section) => section.id)),
97767
+ onReminder: (reminder) => reminders.push(reminder),
97768
+ suggest: (reference2) => suggestedCitation(projectRoot, reference2, request.target.sections)
97599
97769
  });
97600
97770
  const projectedSections = sections.map((section) => ({
97601
97771
  section_ref: `${request.target.article_id}#${section.id}`,
@@ -97604,7 +97774,7 @@ async function composeRevisionCandidate(projectRoot, request, input, options) {
97604
97774
  markdown: section.readerVisibleBody,
97605
97775
  markdown_digest: indexerProtocolDigest(section.readerVisibleBody)
97606
97776
  }));
97607
- return { markdown, metadata, title, references, projectedSections };
97777
+ return { markdown, metadata, title, references, projectedSections, reference_warnings: reminders };
97608
97778
  }
97609
97779
  async function completeApprovedRevision(input) {
97610
97780
  return withProjectWriteLock(input.projectRoot, "compile-approved-revision", async () => {
@@ -97617,7 +97787,7 @@ async function completeApprovedRevision(input) {
97617
97787
  if (request.refresh_sources)
97618
97788
  throw new TypeError("Import the explicitly adjusted source inputs, then run context task adjust with refresh: true before submitting page content.");
97619
97789
  await assertApprovedRevisionBase(input.projectRoot, request);
97620
- const { markdown, metadata, title, references, projectedSections } = await composeRevisionCandidate(input.projectRoot, request, input, { remember: !input.preview });
97790
+ const { markdown, metadata, title, references, projectedSections, reference_warnings } = await composeRevisionCandidate(input.projectRoot, request, input, { remember: !input.preview });
97621
97791
  await assertRevisionRequirements(input.projectRoot, request);
97622
97792
  const approved = request.target.base_digest === null ? undefined : hydrateApprovedKnowledgeMarkdown({
97623
97793
  content: await targetBytes(input.projectRoot, request.target.previous_path ?? request.target.path),
@@ -97660,7 +97830,7 @@ async function completeApprovedRevision(input) {
97660
97830
  },
97661
97831
  updated: new Date().toISOString()
97662
97832
  }, 1);
97663
- const removed = removedCitations(request.target.sections, references);
97833
+ const notes = citationNotes(removedCitations(request.target.sections, references), reference_warnings);
97664
97834
  if (input.preview)
97665
97835
  return {
97666
97836
  protocol: "context.approved-revision-preview/v1",
@@ -97669,10 +97839,10 @@ async function completeApprovedRevision(input) {
97669
97839
  before: request.target.markdown,
97670
97840
  markdown,
97671
97841
  changed: markdown !== request.target.markdown || indexerProtocolDigest(references) !== indexerProtocolDigest(request.target.sections),
97672
- ...removed.length ? { removed_citations: removed, removed_citations_note: REMOVED_CITATIONS_NOTE } : {}
97842
+ ...notes
97673
97843
  };
97674
- if (removed.length)
97675
- input.onRemovedCitations?.(removed);
97844
+ if (Object.keys(notes).length)
97845
+ input.onCitationNotes?.(notes);
97676
97846
  if (request.processed_scopes)
97677
97847
  await captureProcessedScopes(input.projectRoot, request.processed_scopes);
97678
97848
  const approvedSections = validateArticleStructureEntries((await readKnowledgeStructure(input.projectRoot)).parsed?.articles ?? []).find((article) => article.article_id === request.target.article_id)?.sections;
@@ -106795,7 +106965,7 @@ var init_larkMediaDownload = __esm(() => {
106795
106965
 
106796
106966
  // src/lib/larkWhiteboardExport.ts
106797
106967
  import { mkdtemp as mkdtemp5, readFile as readFile91, rm as rm26 } from "node:fs/promises";
106798
- import { tmpdir } from "node:os";
106968
+ import { tmpdir as tmpdir2 } from "node:os";
106799
106969
  import { join as join114 } from "node:path";
106800
106970
  function stableJson2(value) {
106801
106971
  if (value === undefined)
@@ -106826,7 +106996,7 @@ function canonicalWhiteboardPayload(value) {
106826
106996
  };
106827
106997
  }
106828
106998
  async function exportLarkWhiteboardRaw(runner2, identity2, token) {
106829
- const tempRoot = await mkdtemp5(join114(tmpdir(), "context-lark-whiteboard-"));
106999
+ const tempRoot = await mkdtemp5(join114(tmpdir2(), "context-lark-whiteboard-"));
106830
107000
  try {
106831
107001
  await runLarkResourceCommand(runner2, [
106832
107002
  "whiteboard",
@@ -106884,7 +107054,7 @@ var init_larkImagePolicy = __esm(() => {
106884
107054
  import { createHash as createHash36 } from "node:crypto";
106885
107055
  import { mkdtemp as mkdtemp6, readFile as readFile92, readdir as readdir27, rm as rm27 } from "node:fs/promises";
106886
107056
  import { extname as extname12, join as join115 } from "node:path";
106887
- import { tmpdir as tmpdir2 } from "node:os";
107057
+ import { tmpdir as tmpdir3 } from "node:os";
106888
107058
  function countByKind(items, status) {
106889
107059
  const counts2 = new Map;
106890
107060
  for (const item of items) {
@@ -106991,7 +107161,7 @@ async function downloadedFile(input) {
106991
107161
  const bytes = await readFile92(input.localPath);
106992
107162
  return { path: input.localPath, bytes, mediaType: mediaTypeFor(input.localPath, bytes), representation: "original" };
106993
107163
  }
106994
- const tempRoot = await mkdtemp6(join115(tmpdir2(), "context-lark-resource-"));
107164
+ const tempRoot = await mkdtemp6(join115(tmpdir3(), "context-lark-resource-"));
106995
107165
  try {
106996
107166
  const representation = await downloadLarkMedia({ ...input, cwd: tempRoot });
106997
107167
  const entries2 = (await readdir27(tempRoot, { withFileTypes: true })).filter((entry) => entry.isFile());
@@ -107070,7 +107240,7 @@ async function sheetMaterialization(resource, runner2, identity2) {
107070
107240
  const sheetId = resource.attributes["sheet-id"];
107071
107241
  if (token === undefined || sheetId === undefined)
107072
107242
  throw new Error("embedded Sheet requires token and sheet-id");
107073
- const tempRoot = await mkdtemp6(join115(tmpdir2(), "context-lark-sheet-"));
107243
+ const tempRoot = await mkdtemp6(join115(tmpdir3(), "context-lark-sheet-"));
107074
107244
  try {
107075
107245
  const outputPath = join115(tempRoot, "sheet.json");
107076
107246
  const stdout = await runLarkResourceCommand(runner2, [
@@ -109822,19 +109992,19 @@ async function completeCurrentIndexerActionInternal(input) {
109822
109992
  ...content3,
109823
109993
  preview: true
109824
109994
  });
109825
- let removed = [];
109995
+ let notes = {};
109826
109996
  const candidate = await completeApprovedRevision2({
109827
109997
  projectRoot: found.projectRoot,
109828
109998
  revision: input.revision,
109829
109999
  ...content3,
109830
- onRemovedCitations: (items) => {
109831
- removed = items;
110000
+ onCitationNotes: (value) => {
110001
+ notes = value;
109832
110002
  }
109833
110003
  });
109834
110004
  return completedRevisionReceipt(found.projectRoot, semantic.stage, {
109835
110005
  outcome: candidate === undefined ? "unchanged" : "candidate-prepared",
109836
110006
  ...candidate === undefined ? {} : { candidate_id: candidate.candidate_id },
109837
- ...removed.length ? { removed_citations: removed, removed_citations_note: REMOVED_CITATIONS_NOTE } : {}
110007
+ ...notes
109838
110008
  }, input.managed === true, authorities);
109839
110009
  }
109840
110010
  if (semantic.stage === "structure-review") {
@@ -109877,7 +110047,6 @@ async function completedRevisionReceipt(projectRoot2, stage, result, managed, au
109877
110047
  }
109878
110048
  }
109879
110049
  var init_indexerCurrentAction = __esm(() => {
109880
- init_approvedRevisionReferences();
109881
110050
  init_src2();
109882
110051
  init_cliFeedback();
109883
110052
  init_errors3();
@@ -110041,7 +110210,8 @@ async function completeApprovedRevisionSubmission(input) {
110041
110210
  input: task.input,
110042
110211
  outcome: receipt2.outcome ?? "candidate-prepared",
110043
110212
  committed: state === "committed",
110044
- ...receipt2.removed_citations?.length ? { removed_citations: receipt2.removed_citations, removed_citations_note: receipt2.removed_citations_note } : {}
110213
+ ...receipt2.removed_citations?.length ? { removed_citations: receipt2.removed_citations, removed_citations_note: receipt2.removed_citations_note } : {},
110214
+ ...receipt2.reference_warnings?.length ? { reference_warnings: receipt2.reference_warnings, reference_warning_instruction: receipt2.reference_warning_instruction } : {}
110045
110215
  });
110046
110216
  workflow = receipt2.workflow;
110047
110217
  const next2 = workflow?.current;
@@ -110119,7 +110289,7 @@ async function previewApprovedRevisionSubmission(input) {
110119
110289
  return first < 0 || !issuedTask || !now2 || issuedTask.task !== fixed2.tasks[index3].task || issuedTask.input !== fixed2.tasks[index3].input || now2.revision !== issuedTask.revision || now2.context !== issuedTask.context;
110120
110290
  };
110121
110291
  const { composeRevisionCandidate: composeRevisionCandidate2 } = await Promise.resolve().then(() => (init_approvedRevision(), exports_approvedRevision));
110122
- const { SubmissionInputError: SubmissionInputError2 } = await Promise.resolve().then(() => (init_productionFeedback(), exports_productionFeedback));
110292
+ const { SubmissionInputError: SubmissionInputError2, SubmissionInputErrors: SubmissionInputErrors2 } = await Promise.resolve().then(() => (init_productionFeedback(), exports_productionFeedback));
110123
110293
  const issue = (error) => error instanceof SubmissionInputError2 ? { message: error.message, path: error.path, ...error.reason ? { reason_code: error.reason } : {} } : error instanceof exports_external.ZodError ? { message: error.issues.map((item) => item.message).join("; ") } : { message: error instanceof Error ? error.message : String(error) };
110124
110294
  const pages = [];
110125
110295
  for (const [index3, task] of fixed2.tasks.entries()) {
@@ -110145,18 +110315,17 @@ async function previewApprovedRevisionSubmission(input) {
110145
110315
  throw new TypeError(`Task ${task.task} is not an approved revision.`);
110146
110316
  const request = JSON.parse((await readProductionFile({ projectRoot: input.projectRoot, stage: manifest.stage, path: `${task.task}.input.json` })).text);
110147
110317
  const content3 = "markdown" in semantic ? { markdown: semantic.markdown, ...semantic.sections === undefined ? {} : { sections: semantic.sections } } : { sections: semantic.sections };
110148
- const { markdown, references } = await composeRevisionCandidate2(input.projectRoot, request, content3, { remember: false });
110149
- const removed = removedCitations(request.target.sections, references);
110318
+ const { markdown, references, reference_warnings } = await composeRevisionCandidate2(input.projectRoot, request, content3, { remember: false });
110150
110319
  pages.push({
110151
110320
  task: task.task,
110152
110321
  path: request.target.path,
110153
110322
  ok: true,
110154
110323
  issues: [],
110155
110324
  changed: markdown !== request.target.markdown || indexerProtocolDigest(references) !== indexerProtocolDigest(request.target.sections),
110156
- ...removed.length ? { removed_citations: removed, removed_citations_note: REMOVED_CITATIONS_NOTE } : {}
110325
+ ...citationNotes(removedCitations(request.target.sections, references), reference_warnings)
110157
110326
  });
110158
110327
  } catch (error) {
110159
- pages.push({ task: task.task, ok: false, issues: [issue(error)] });
110328
+ pages.push({ task: task.task, ok: false, issues: error instanceof SubmissionInputErrors2 ? error.errors.map(issue) : [issue(error)] });
110160
110329
  }
110161
110330
  }
110162
110331
  const reissue = pages.some((page) => page.issues.some((issue2) => issue2.reason_code === "task-input-stale"));
@@ -117676,14 +117845,16 @@ async function executeClose(cwd, command2) {
117676
117845
  throw new Error("unsupported close command");
117677
117846
  await runProjectCloseCommand({ cwd, format: outputFormat(options) ?? "text" });
117678
117847
  }
117679
- async function executeBuild(cwd, command2) {
117848
+ async function executeBuild(cwd, invocation) {
117849
+ const command2 = invocation.command;
117680
117850
  const options = parseOptions(command2.slice(1), new Set(["--format"]), new Set(["--verbose"]));
117681
117851
  if (options === undefined || options.positionals.length > 0)
117682
117852
  throw new Error("unsupported build command");
117683
117853
  await runProjectBuildCommand({
117684
117854
  cwd,
117685
117855
  format: outputFormat(options) ?? "text",
117686
- verbose: options.flags.has("--verbose")
117856
+ verbose: options.flags.has("--verbose"),
117857
+ execution: { managed: invocation.managed, authorities: invocation.authorities }
117687
117858
  });
117688
117859
  }
117689
117860
  async function executeReviewApproveAll(cwd, invocation) {
@@ -117740,7 +117911,7 @@ async function executeCommand(cwd, invocation) {
117740
117911
  return;
117741
117912
  }
117742
117913
  if (command2 === "build") {
117743
- await executeBuild(cwd, invocation.command);
117914
+ await executeBuild(cwd, invocation);
117744
117915
  return;
117745
117916
  }
117746
117917
  if (command2 === "review" && subcommand === "approve-all") {
@@ -118378,6 +118549,22 @@ function requireProjectRoot2() {
118378
118549
  category: ErrorCategory.WorkspaceNotFound
118379
118550
  });
118380
118551
  }
118552
+ async function withNextRoute(program2, projectRoot, result) {
118553
+ const next2 = result?.next_action?.command;
118554
+ if (next2 !== "context status --format json")
118555
+ return result;
118556
+ try {
118557
+ const [{ collectProjectStatus: collectProjectStatus2 }, { workflowAuthorities: workflowAuthorities2 }] = await Promise.all([
118558
+ Promise.resolve().then(() => (init_status(), exports_status)),
118559
+ Promise.resolve().then(() => (init_workflowCommandOptions(), exports_workflowCommandOptions))
118560
+ ]);
118561
+ const root2 = program2.opts();
118562
+ const status = await collectProjectStatus2(projectRoot, { managed: root2.workflowManaged === true, authorities: workflowAuthorities2(root2.workflowAuthority) });
118563
+ return { ...result, workflow: status.workflow };
118564
+ } catch {
118565
+ return result;
118566
+ }
118567
+ }
118381
118568
  function registerDocumentRevisionCommand(program2) {
118382
118569
  const task = program2.command("task").description("Explicit current-task recovery");
118383
118570
  task.command("retire").description("Preview or apply explicit approved-article retirement and reference cleanup").option("--input <file>", "YAML/JSON reason and targets with optional approved replacement; - for stdin").option("--schema", "show the retirement input schema").option("--apply", "apply the reviewed retirement within existing user authorization").option("--plan-digest <digest>", "exact current retirement preview").option("--format <format>", "output format: json", "json").action(async (options) => {
@@ -118493,7 +118680,8 @@ function registerDocumentRevisionCommand(program2) {
118493
118680
  parseFailureNext: "Provide valid YAML or JSON."
118494
118681
  });
118495
118682
  const { registerKnowledgeMaintenance: registerKnowledgeMaintenance2 } = await Promise.resolve().then(() => (init_knowledgeMaintenance(), exports_knowledgeMaintenance));
118496
- process.stdout.write(`${JSON.stringify(await registerKnowledgeMaintenance2(requireProjectRoot2(), value))}
118683
+ const projectRoot = requireProjectRoot2();
118684
+ process.stdout.write(`${JSON.stringify(await withNextRoute(program2, projectRoot, await registerKnowledgeMaintenance2(projectRoot, value)))}
118497
118685
  `);
118498
118686
  });
118499
118687
  task.command("record-fix").description("Record a mechanical correction made after the batch's approval and before its delivery").option("--input <file>", "YAML/JSON path and reason; - for stdin").option("--format <format>", "output format: json", "json").action(async (options) => {
@@ -118518,7 +118706,8 @@ function registerDocumentRevisionCommand(program2) {
118518
118706
  if (options.format !== "json")
118519
118707
  throw new TypeError("--format must be json");
118520
118708
  const { advanceKnowledgeMaintenance: advanceKnowledgeMaintenance2 } = await Promise.resolve().then(() => (init_knowledgeMaintenance(), exports_knowledgeMaintenance));
118521
- process.stdout.write(`${JSON.stringify(await advanceKnowledgeMaintenance2(requireProjectRoot2(), options.revision))}
118709
+ const projectRoot = requireProjectRoot2();
118710
+ process.stdout.write(`${JSON.stringify(await withNextRoute(program2, projectRoot, await advanceKnowledgeMaintenance2(projectRoot, options.revision)))}
118522
118711
  `);
118523
118712
  });
118524
118713
  task.command("maintenance-status").description("Inspect maintenance requests and the current cancellation revision").option("--format <format>", "output format: json", "json").action(async (options) => {
@@ -118657,10 +118846,20 @@ function registerVersionCommands(program2) {
118657
118846
  if (!root2)
118658
118847
  throw new TypeError("Run inside a Context workspace");
118659
118848
  const { files: _, content_digest: _digest, snapshot_format: _format, ...status } = await inspectWorkspaceVersion(root2, options.base);
118849
+ const first = status.version === "0.0.0";
118850
+ const [major, minor, patch] = status.version.split(".").map(Number);
118851
+ const suggested = status.reusable_version ?? (first ? "0.1.0" : `${major}.${minor}.${patch + 1}`);
118660
118852
  process.stdout.write(JSON.stringify({
118661
118853
  ...status,
118662
118854
  next_action: { command: "context version record --input <file> --format json" },
118663
- input_example: { expected_digest: status.expected_digest, ...options.base ? { base_ref: options.base } : {}, version: "0.1.0", title: "Summary", changes: ["Reader-visible changes"], triggers: [{ kind: "initial", description: "User requested initial knowledge production" }] }
118855
+ input_example: {
118856
+ expected_digest: status.expected_digest,
118857
+ ...options.base ? { base_ref: options.base } : {},
118858
+ version: suggested,
118859
+ title: "Summary",
118860
+ changes: ["Reader-visible changes"],
118861
+ triggers: [first ? { kind: "initial", description: "User requested initial knowledge production" } : { kind: "other", description: "What caused this change" }]
118862
+ }
118664
118863
  }, null, 2) + `
118665
118864
  `);
118666
118865
  });
@@ -118956,9 +119155,10 @@ async function prepareActionCompletionOutput(input) {
118956
119155
  ...Array.isArray(result.reference_warnings) ? { reference_warning_count: result.reference_warnings.length } : {},
118957
119156
  ...Array.isArray(result.removed_citations) && result.removed_citations.length ? pick(result, ["removed_citations", "removed_citations_note"]) : {},
118958
119157
  ...result.removed_citations_note === undefined && outcomes.some((item) => Array.isArray(item.removed_citations)) ? { removed_citations_note: outcomes.find((item) => item.removed_citations_note !== undefined)?.removed_citations_note } : {},
119158
+ ...result.reference_warning_instruction === undefined && outcomes.some((item) => Array.isArray(item.reference_warnings)) ? { reference_warning_instruction: outcomes.find((item) => item.reference_warning_instruction !== undefined)?.reference_warning_instruction } : {},
118959
119159
  committed_count: Array.isArray(result.outcomes) ? outcomes.filter((item) => item.committed === true).length : null,
118960
119160
  outcomes: outcomes.map((item) => ({
118961
- ...pick(item, ["task_key", "outcome", "committed", "removed_citations"]),
119161
+ ...pick(item, ["task_key", "outcome", "committed", "removed_citations", "reference_warnings"]),
118962
119162
  ...item.message === undefined ? {} : { message: shortText(item.message) }
118963
119163
  })),
118964
119164
  outcomes_omitted: 0,
@@ -119441,7 +119641,7 @@ async function repositoryRecoveryPlan(input) {
119441
119641
  command: "context source restore --input .tmp/agent-payloads/repository-source-recovery.json --format json",
119442
119642
  input: ".tmp/agent-payloads/repository-source-recovery.json",
119443
119643
  input_example: { schema: RECOVERY_SCHEMA, repositories: groups.filter((group) => !group.ready).map((group) => ({ source: group.sources[0], mode: "clone" })) },
119444
- input_note: "Save input_example as the input file. Each entry restores every source of its group. " + "To reuse an existing checkout instead of cloning, set mode to local and add path."
119644
+ input_note: "Save input_example as the input file. Each entry restores every source of its group. " + "mode clone is already small: a shallow, partial clone of the registered commit that checks out only the group's required_subpaths. " + "To reuse an existing checkout instead of cloning, set mode to local and add path."
119445
119645
  }
119446
119646
  };
119447
119647
  }
@@ -123282,10 +123482,13 @@ function registerProjectCloseAndBuildCommands(program2) {
123282
123482
  category: ErrorCategory.UserInputInvalid
123283
123483
  });
123284
123484
  }
123485
+ const { workflowAuthorities: workflowAuthorities2 } = await Promise.resolve().then(() => (init_workflowCommandOptions(), exports_workflowCommandOptions));
123486
+ const root2 = program2.opts();
123285
123487
  if (await runProjectBuildCommand({
123286
123488
  cwd: process.cwd(),
123287
123489
  format: options.format === "json" ? "json" : "text",
123288
- verbose: options.verbose === true
123490
+ verbose: options.verbose === true,
123491
+ execution: { managed: root2.workflowManaged === true, authorities: workflowAuthorities2(root2.workflowAuthority) }
123289
123492
  })) {
123290
123493
  return;
123291
123494
  }
@@ -123380,6 +123583,21 @@ async function digest9(root2) {
123380
123583
  await visit4(root2, "");
123381
123584
  return hash5.digest("hex");
123382
123585
  }
123586
+ async function assertOwnedDirectory(target, existing) {
123587
+ if (!existing.isDirectory() || existing.isSymbolicLink())
123588
+ conflict(target);
123589
+ const markerPath = join140(target, MARKER);
123590
+ if (!(await stat11(markerPath))?.isFile())
123591
+ conflict(target);
123592
+ let marker;
123593
+ try {
123594
+ marker = JSON.parse(await readFile115(markerPath, "utf8"));
123595
+ } catch {
123596
+ conflict(target);
123597
+ }
123598
+ if (marker?.owner !== "context-plugin-local" || marker.digest !== await digest9(target))
123599
+ conflict(target);
123600
+ }
123383
123601
  async function installLocalSkills(root2, path3, dryRun, agent) {
123384
123602
  if (!path3.trim())
123385
123603
  conflict("--local requires a non-empty path");
@@ -123399,14 +123617,7 @@ async function installLocalSkills(root2, path3, dryRun, agent) {
123399
123617
  for (const entry of await readdir35(join140(root2, agent, "commands"), { withFileTypes: true })) {
123400
123618
  if (!entry.isFile() || !entry.name.endsWith(".md"))
123401
123619
  continue;
123402
- let content3 = await readFile115(join140(root2, agent, "commands", entry.name), "utf8");
123403
- if (agent === "claude" && !["context-plan.md", "context-repo-content.md"].includes(entry.name)) {
123404
- const frontmatter2 = /^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/.exec(content3);
123405
- if (!frontmatter2)
123406
- conflict(join140(root2, agent, "commands", entry.name));
123407
- content3 = `${frontmatter2[1]}disable-model-invocation: true
123408
- ${frontmatter2[2].replace(/^disable-model-invocation:.*\r?\n?/mu, "")}${frontmatter2[3]}${content3.slice(frontmatter2[0].length)}`;
123409
- }
123620
+ const content3 = await readFile115(join140(root2, agent, "commands", entry.name), "utf8");
123410
123621
  const target = join140(commandsRoot, entry.name);
123411
123622
  const marker = join140(commandsRoot, `.context-${entry.name}.json`);
123412
123623
  for (const file of [target, marker]) {
@@ -123443,35 +123654,43 @@ ${frontmatter2[2].replace(/^disable-model-invocation:.*\r?\n?/mu, "")}${frontmat
123443
123654
  continue;
123444
123655
  }
123445
123656
  const existing = await stat11(target);
123446
- if (existing) {
123447
- if (!existing.isDirectory() || existing.isSymbolicLink())
123448
- conflict(target);
123449
- const markerPath = join140(target, MARKER);
123450
- if (!(await stat11(markerPath))?.isFile())
123451
- conflict(target);
123452
- let marker;
123453
- try {
123454
- marker = JSON.parse(await readFile115(markerPath, "utf8"));
123455
- } catch {
123456
- conflict(target);
123457
- }
123458
- if (marker?.owner !== "context-plugin-local" || marker.digest !== await digest9(target))
123459
- conflict(target);
123460
- }
123657
+ if (existing)
123658
+ await assertOwnedDirectory(target, existing);
123461
123659
  plans.push({ name: entry.name, source: source2, target, hash: await digest9(source2), exists: !!existing });
123462
123660
  }
123463
123661
  if (!plans.length)
123464
123662
  conflict(sourceRoot);
123663
+ const resourcePlans = [];
123664
+ const resourcesRoot = join140(targetRoot, "resources");
123665
+ if (agent === "claude" || agent === "cursor") {
123666
+ const resourceSource = join140(root2, agent, "resources");
123667
+ if (await stat11(resourceSource)) {
123668
+ await checkParents(resourcesRoot);
123669
+ for (const entry of (await readdir35(resourceSource, { withFileTypes: true })).sort((a2, b) => a2.name.localeCompare(b.name))) {
123670
+ if (!entry.isDirectory())
123671
+ continue;
123672
+ const source2 = join140(resourceSource, entry.name);
123673
+ const target = join140(resourcesRoot, entry.name);
123674
+ const existing = await stat11(target);
123675
+ if (existing)
123676
+ await assertOwnedDirectory(target, existing);
123677
+ resourcePlans.push({ name: entry.name, source: source2, target, hash: await digest9(source2), exists: !!existing });
123678
+ }
123679
+ }
123680
+ }
123465
123681
  if (!dryRun) {
123466
123682
  await mkdir45(skillsRoot, { recursive: true });
123467
- for (const plan of plans) {
123468
- const staging = await mkdtemp7(join140(skillsRoot, ".context-install-"));
123683
+ if (resourcePlans.length)
123684
+ await mkdir45(resourcesRoot, { recursive: true });
123685
+ for (const plan of [...plans, ...resourcePlans]) {
123686
+ const resource = resourcePlans.includes(plan);
123687
+ const staging = await mkdtemp7(join140(dirname54(plan.target), ".context-install-"));
123469
123688
  const candidate = join140(staging, "candidate");
123470
123689
  const previous3 = join140(staging, "previous");
123471
123690
  let moved = false;
123472
123691
  try {
123473
123692
  await cp3(plan.source, candidate, { recursive: true });
123474
- if (agent === "claude" || agent === "cursor" && ["context-plan", "context-repo-content"].includes(plan.name)) {
123693
+ if (!resource && (agent === "claude" || agent === "cursor" && ["context-plan", "context-repo-content"].includes(plan.name))) {
123475
123694
  const skillFile = join140(candidate, "SKILL.md");
123476
123695
  const content3 = await readFile115(skillFile, "utf8");
123477
123696
  const parts = /^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/.exec(content3);
@@ -123524,7 +123743,8 @@ ${frontmatter2}${parts[3]}${content3.slice(parts[0].length)}`);
123524
123743
  ...agent === "codex" ? ["Codex uses skill entries, not a commands directory; bundled invocation policies are preserved."] : [],
123525
123744
  ...agent === "cursor" ? ["Cursor command entries are separated; hiding Provider skills from its command menu is not guaranteed."] : [],
123526
123745
  ...plans.map((plan) => `skills/${plan.name}`),
123527
- ...commandPlans.map((plan) => `commands/${plan.name}`)
123746
+ ...commandPlans.map((plan) => `commands/${plan.name}`),
123747
+ ...resourcePlans.map((plan) => `resources/${plan.name}`)
123528
123748
  ]
123529
123749
  });
123530
123750
  }