@c4a/context-cli 0.7.104 → 0.7.106
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 +754 -461
- package/indexers/contracts/profile-contract.json +245 -245
- package/indexers/release-manifest.json +1 -1
- package/package.json +12 -12
- package/parserEntryWorker.js +3 -1
- package/plugins/VERSION +1 -1
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/commands/context.md +7 -5
- package/plugins/claude/resources/context/routine-update.md +37 -26
- package/plugins/claude/skills/context-plan/SKILL.md +4 -2
- package/plugins/claude/skills/context-plan/references/project-planning.md +9 -1
- package/plugins/codex/.codex-plugin/plugin.json +2 -2
- package/plugins/codex/skills/context/SKILL.md +7 -5
- package/plugins/codex/skills/context/references/routine-update.md +37 -26
- package/plugins/codex/skills/context-plan/SKILL.md +4 -2
- package/plugins/codex/skills/context-plan/references/project-planning.md +9 -1
- package/plugins/cursor/.cursor-plugin/plugin.json +1 -1
- package/plugins/cursor/commands/c4a-context.md +7 -5
- package/plugins/cursor/resources/context/routine-update.md +37 -26
- package/plugins/cursor/skills/context-plan/SKILL.md +4 -2
- package/plugins/cursor/skills/context-plan/references/project-planning.md +9 -1
- package/plugins/skills/context/SKILL.md +7 -5
- package/plugins/skills/context/references/routine-update.md +37 -26
- package/plugins/skills/context-plan/SKILL.md +4 -2
- package/plugins/skills/context-plan/references/project-planning.md +9 -1
- package/providers/context/manifest.json +14 -14
- package/providers/context/provider.yaml +1 -1
- package/providers/context/resources/manuals/guides/knowledge-updates.md +66 -0
- package/providers/context/resources/manuals/guides/lark-resources.md +21 -1
- package/providers/context/resources/procedures/approved-revision.md +6 -1
- package/providers/context/resources/procedures/document-capture.md +8 -0
- package/providers/context/resources/procedures/knowledge-updates.md +66 -0
- package/providers/context/resources/procedures/source-update.md +14 -0
package/cli.js
CHANGED
|
@@ -40810,7 +40810,7 @@ var getSourceType = (sourceDefinition) => {
|
|
|
40810
40810
|
}), captureLark = (definition) => {
|
|
40811
40811
|
const sourceDefinition = bindSourceType(definition.source, "lark", "captureLark source");
|
|
40812
40812
|
const sourceId = getSourceName(sourceDefinition);
|
|
40813
|
-
for (const key of ["images", "gifs"]) {
|
|
40813
|
+
for (const key of ["images", "gifs", "files", "whiteboards"]) {
|
|
40814
40814
|
const value = definition.resources?.[key];
|
|
40815
40815
|
if (value !== undefined && value !== "bundle" && value !== "reference-only") {
|
|
40816
40816
|
throw new TypeError(`captureLark resources.${key} must be bundle or reference-only`);
|
|
@@ -40836,6 +40836,8 @@ var getSourceType = (sourceDefinition) => {
|
|
|
40836
40836
|
resources: {
|
|
40837
40837
|
...definition.resources?.images === undefined ? {} : { images: definition.resources.images },
|
|
40838
40838
|
...definition.resources?.gifs === undefined ? {} : { gifs: definition.resources.gifs },
|
|
40839
|
+
...definition.resources?.files === undefined ? {} : { files: definition.resources.files },
|
|
40840
|
+
...definition.resources?.whiteboards === undefined ? {} : { whiteboards: definition.resources.whiteboards },
|
|
40839
40841
|
videos: definition.resources?.videos ?? "reference-only",
|
|
40840
40842
|
maxBytesPerResource,
|
|
40841
40843
|
maxTotalBytes
|
|
@@ -71019,10 +71021,7 @@ async function registeredRepoHistoryReader(projectRoot) {
|
|
|
71019
71021
|
const entry = registry2.repos.find((item) => item.id === name2 || item.name === name2);
|
|
71020
71022
|
if (!entry)
|
|
71021
71023
|
throw new TypeError(`Source is not a registered repository: ${sourceRef}`);
|
|
71022
|
-
root = realpath6(resolve19(workspace, entry.materializedAt))
|
|
71023
|
-
inside(workspace, actual);
|
|
71024
|
-
return actual;
|
|
71025
|
-
});
|
|
71024
|
+
root = realpath6(resolve19(workspace, entry.materializedAt));
|
|
71026
71025
|
roots.set(sourceRef, root);
|
|
71027
71026
|
}
|
|
71028
71027
|
const directory = await root;
|
|
@@ -71078,7 +71077,8 @@ async function registeredArticleSourceReader(projectRoot) {
|
|
|
71078
71077
|
throw new SourceReadError(`The registered source checkout of ${sourceRef} is not accessible. Restore the source before checking citations.`, "context source recovery-plan --format json");
|
|
71079
71078
|
throw error;
|
|
71080
71079
|
});
|
|
71081
|
-
|
|
71080
|
+
if (kind !== "repo")
|
|
71081
|
+
inside(workspace, root);
|
|
71082
71082
|
if (managed)
|
|
71083
71083
|
return { root, files: new Map([[basename3(entry.materializedAt), ""]]) };
|
|
71084
71084
|
if (kind === "repo") {
|
|
@@ -78547,6 +78547,154 @@ var init_referenceRangeMap = __esm(() => {
|
|
|
78547
78547
|
exec2 = promisify4(execFile5);
|
|
78548
78548
|
});
|
|
78549
78549
|
|
|
78550
|
+
// src/project/productionFeedback.ts
|
|
78551
|
+
var exports_productionFeedback = {};
|
|
78552
|
+
__export(exports_productionFeedback, {
|
|
78553
|
+
withProductionFeedback: () => withProductionFeedback,
|
|
78554
|
+
SubmissionInputErrors: () => SubmissionInputErrors,
|
|
78555
|
+
SubmissionInputError: () => SubmissionInputError
|
|
78556
|
+
});
|
|
78557
|
+
async function withProductionFeedback(input, run) {
|
|
78558
|
+
try {
|
|
78559
|
+
return await run();
|
|
78560
|
+
} catch (error) {
|
|
78561
|
+
const schemaError = error instanceof ZodError;
|
|
78562
|
+
const inputError = error instanceof SubmissionInputError;
|
|
78563
|
+
const syntaxError = error instanceof import_yaml15.YAMLParseError;
|
|
78564
|
+
const existing = error instanceof ContextError ? error : undefined;
|
|
78565
|
+
const ioCode = error?.code;
|
|
78566
|
+
const detail = {
|
|
78567
|
+
category: schemaError || syntaxError || inputError ? ErrorCategory.UserInputInvalid : ErrorCategory.WorkspaceStateInvalid,
|
|
78568
|
+
reason_code: `production-${input.operation}-failed`,
|
|
78569
|
+
next_action: { command: "context status --format json", ...input.recovery ? { instruction: input.recovery } : inputError ? { instruction: "Correct the reported item in the input file and resubmit it with the same revision." } : {} },
|
|
78570
|
+
...input.file ? { file: input.file } : {},
|
|
78571
|
+
...schemaError ? { issues: error.issues.map((issue) => ({ path: issue.path, message: issue.message })) } : {},
|
|
78572
|
+
...inputError ? { issues: [{ path: error.path, message: error.message }], ...error.reason ? { reason_code: error.reason } : {} } : {},
|
|
78573
|
+
...syntaxError && error.linePos ? { location: error.linePos } : {},
|
|
78574
|
+
...typeof ioCode === "string" ? { io_code: ioCode } : {},
|
|
78575
|
+
...existing?.detail
|
|
78576
|
+
};
|
|
78577
|
+
if (input.schema && detail.input_schema === undefined) {
|
|
78578
|
+
detail.input_schema = zodToJsonSchema(input.schema, { $refStrategy: "none" });
|
|
78579
|
+
}
|
|
78580
|
+
throw new ContextError(existing?.code ?? (schemaError || syntaxError || inputError ? ExitCode.UserError : ExitCode.WorkspaceStateError), error instanceof Error ? error.message : String(error), detail);
|
|
78581
|
+
}
|
|
78582
|
+
}
|
|
78583
|
+
var import_yaml15, SubmissionInputError, SubmissionInputErrors;
|
|
78584
|
+
var init_productionFeedback = __esm(() => {
|
|
78585
|
+
init_zod();
|
|
78586
|
+
init_esm();
|
|
78587
|
+
init_errors3();
|
|
78588
|
+
init_cliFeedback();
|
|
78589
|
+
init_exitCode();
|
|
78590
|
+
import_yaml15 = __toESM(require_dist(), 1);
|
|
78591
|
+
SubmissionInputError = class SubmissionInputError extends TypeError {
|
|
78592
|
+
path;
|
|
78593
|
+
reason;
|
|
78594
|
+
constructor(message, path2 = [], reason) {
|
|
78595
|
+
super(message);
|
|
78596
|
+
this.path = path2;
|
|
78597
|
+
this.reason = reason;
|
|
78598
|
+
}
|
|
78599
|
+
};
|
|
78600
|
+
SubmissionInputErrors = class SubmissionInputErrors extends SubmissionInputError {
|
|
78601
|
+
errors;
|
|
78602
|
+
constructor(errors4) {
|
|
78603
|
+
super(`${errors4.length} problems: ${errors4.map((error, index2) => `(${index2 + 1}) ${error.message}`).join(" ")}`, errors4[0]?.path ?? [], errors4[0]?.reason);
|
|
78604
|
+
this.errors = errors4;
|
|
78605
|
+
}
|
|
78606
|
+
};
|
|
78607
|
+
});
|
|
78608
|
+
|
|
78609
|
+
// src/project/submittedSourceLocator.ts
|
|
78610
|
+
function assertNoCaptureGap(locator, capturedText) {
|
|
78611
|
+
const lines = capturedText.replace(/\r\n/gu, `
|
|
78612
|
+
`).split(`
|
|
78613
|
+
`).slice(locator.start_line - 1, locator.end_line);
|
|
78614
|
+
const gapOnly = (line) => CAPTURE_GAP.test(line) && line.replace(new RegExp(CAPTURE_GAP.source, "gu"), "").replace(/<br\s*\/?>|[|>\s]/giu, "") === "";
|
|
78615
|
+
const gap = lines.findIndex(gapOnly);
|
|
78616
|
+
if (gap >= 0)
|
|
78617
|
+
throw new SubmissionInputError(`${locator.path}:${locator.start_line + gap} is a capture gap (the resource was not captured), ` + "not evidence. Cite only captured lines; the missing content cannot support a claim until it is captured.");
|
|
78618
|
+
}
|
|
78619
|
+
function exactQuoteLocator(locator, capturedText, maxLength) {
|
|
78620
|
+
const text5 = capturedText.replace(/\r\n/gu, `
|
|
78621
|
+
`);
|
|
78622
|
+
try {
|
|
78623
|
+
const quote2 = articleSourceRegion(text5, locator);
|
|
78624
|
+
if (quote2.trim() === "" || quote2.length > maxLength)
|
|
78625
|
+
return;
|
|
78626
|
+
const resolved = resolveSubmittedSourceLocator({ path: locator.path, quote: quote2 }, text5);
|
|
78627
|
+
if (resolved.start_line !== locator.start_line || resolved.end_line !== locator.end_line)
|
|
78628
|
+
return;
|
|
78629
|
+
assertNoCaptureGap(resolved, text5);
|
|
78630
|
+
return { path: locator.path, quote: quote2 };
|
|
78631
|
+
} catch {
|
|
78632
|
+
return;
|
|
78633
|
+
}
|
|
78634
|
+
}
|
|
78635
|
+
function resolveSubmittedSourceLocator(input, capturedText) {
|
|
78636
|
+
const locator = submittedSourceLocatorSchema.parse(input);
|
|
78637
|
+
if ("start_line" in locator)
|
|
78638
|
+
return locator;
|
|
78639
|
+
const text5 = capturedText.replace(/\r\n/gu, `
|
|
78640
|
+
`);
|
|
78641
|
+
const lines = text5.split(`
|
|
78642
|
+
`);
|
|
78643
|
+
const matches = [];
|
|
78644
|
+
if ("quote" in locator) {
|
|
78645
|
+
const quote2 = locator.quote.replace(/\r\n/gu, `
|
|
78646
|
+
`);
|
|
78647
|
+
for (let offset2 = text5.indexOf(quote2);offset2 >= 0; offset2 = text5.indexOf(quote2, offset2 + 1)) {
|
|
78648
|
+
matches.push({
|
|
78649
|
+
start_line: text5.slice(0, offset2).split(`
|
|
78650
|
+
`).length,
|
|
78651
|
+
end_line: text5.slice(0, offset2 + quote2.length - 1).split(`
|
|
78652
|
+
`).length
|
|
78653
|
+
});
|
|
78654
|
+
}
|
|
78655
|
+
} else {
|
|
78656
|
+
if (!/\.(?:md|markdown|mdx)$/iu.test(locator.path))
|
|
78657
|
+
throw new SubmissionInputError("heading requires a Markdown source; use quote or start_line/end_line instead.");
|
|
78658
|
+
const marked = /^(#{1,6})[ \t]+(.+)$/u.exec(locator.heading.trim());
|
|
78659
|
+
const wanted = { level: marked?.[1].length, title: (marked?.[2] ?? locator.heading).trim() };
|
|
78660
|
+
const headings = [];
|
|
78661
|
+
let fence;
|
|
78662
|
+
for (const [index2, line] of lines.entries()) {
|
|
78663
|
+
const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(line);
|
|
78664
|
+
if (fence) {
|
|
78665
|
+
if (marker && marker[1][0] === fence.character && marker[1].length >= fence.length && !marker[2].trim())
|
|
78666
|
+
fence = undefined;
|
|
78667
|
+
continue;
|
|
78668
|
+
}
|
|
78669
|
+
if (marker) {
|
|
78670
|
+
fence = { character: marker[1][0], length: marker[1].length };
|
|
78671
|
+
continue;
|
|
78672
|
+
}
|
|
78673
|
+
const match = /^ {0,3}(#{1,6})(?:[ \t]+(.*)|[ \t]*)$/u.exec(line);
|
|
78674
|
+
if (match)
|
|
78675
|
+
headings.push({ line: index2 + 1, level: match[1].length, title: (match[2] ?? "").replace(/[ \t]+#+[ \t]*$/u, "").trim() });
|
|
78676
|
+
}
|
|
78677
|
+
for (const [index2, heading] of headings.entries()) {
|
|
78678
|
+
if (heading.title !== wanted.title || wanted.level !== undefined && heading.level !== wanted.level)
|
|
78679
|
+
continue;
|
|
78680
|
+
let end = (headings.slice(index2 + 1).find((next) => next.level <= heading.level)?.line ?? lines.length + 1) - 1;
|
|
78681
|
+
while (end > heading.line && !lines[end - 1].trim())
|
|
78682
|
+
end--;
|
|
78683
|
+
matches.push({ start_line: heading.line, end_line: end });
|
|
78684
|
+
}
|
|
78685
|
+
}
|
|
78686
|
+
if (matches.length !== 1)
|
|
78687
|
+
throw new SubmissionInputError(`Source locator matched ${matches.length} regions in ${locator.path}; candidates: ${matches.slice(0, 5).map((m) => `${m.start_line}-${m.end_line}`).join(", ") || "none"}. Use a unique heading/quote or explicit start_line/end_line.`);
|
|
78688
|
+
return articleSourceLocatorSchema.parse({ path: locator.path, ...matches[0] });
|
|
78689
|
+
}
|
|
78690
|
+
var submittedSourceLocatorSchema, CAPTURE_GAP;
|
|
78691
|
+
var init_submittedSourceLocator = __esm(() => {
|
|
78692
|
+
init_src2();
|
|
78693
|
+
init_productionFeedback();
|
|
78694
|
+
submittedSourceLocatorSchema = articleSourceLocatorInputSchema;
|
|
78695
|
+
CAPTURE_GAP = /(?:> ?)?Resource unavailable: .+? \([^;()]+; [^()]+\)\. <!-- [^>]+ -->/u;
|
|
78696
|
+
});
|
|
78697
|
+
|
|
78550
78698
|
// src/project/articleReferenceObservation.ts
|
|
78551
78699
|
import { createHash as createHash13 } from "node:crypto";
|
|
78552
78700
|
import { execFile as execFile6 } from "node:child_process";
|
|
@@ -78620,14 +78768,14 @@ async function suggestedRange(root, reference2, before, current3, cited, clip =
|
|
|
78620
78768
|
locator: { path: mapped.path, start_line: mapped.start_line, end_line: mapped.end_line },
|
|
78621
78769
|
message: "The source diff maps the old lines here. If this text still supports the section, cite this locator; it is checked again on submit."
|
|
78622
78770
|
};
|
|
78623
|
-
const
|
|
78624
|
-
if (!
|
|
78771
|
+
const quote2 = exactQuoteLocator(mapped, normalized, 4000);
|
|
78772
|
+
if (!quote2)
|
|
78625
78773
|
return;
|
|
78626
78774
|
return {
|
|
78627
78775
|
start_line: mapped.start_line,
|
|
78628
78776
|
end_line: mapped.end_line,
|
|
78629
78777
|
...clip(region),
|
|
78630
|
-
locator:
|
|
78778
|
+
locator: quote2,
|
|
78631
78779
|
message: "An earlier citation used these line numbers, and repeating them keeps that earlier evidence; to cite the new text here, use this quote locator."
|
|
78632
78780
|
};
|
|
78633
78781
|
}
|
|
@@ -78731,6 +78879,7 @@ var init_articleReferenceObservation = __esm(() => {
|
|
|
78731
78879
|
init_articleSourceReader();
|
|
78732
78880
|
init_gitObjectReader();
|
|
78733
78881
|
init_referenceRangeMap();
|
|
78882
|
+
init_submittedSourceLocator();
|
|
78734
78883
|
LOCAL_SOURCE_REASONS = {
|
|
78735
78884
|
"source-content-missing": "The cited file contents are not downloaded in the source checkout.",
|
|
78736
78885
|
"source-history-missing": "The registered commit is not in the source checkout."
|
|
@@ -78999,7 +79148,7 @@ async function writeRepoRegistry(projectRoot, registry2) {
|
|
|
78999
79148
|
modules.push(registryRecordToYaml(record4));
|
|
79000
79149
|
namespaces.set(record4.namespace, modules);
|
|
79001
79150
|
}
|
|
79002
|
-
await atomicWriteFile(path2,
|
|
79151
|
+
await atomicWriteFile(path2, import_yaml16.default.stringify({
|
|
79003
79152
|
sources: [...namespaces].map(([name2, modules]) => ({ name: name2, modules }))
|
|
79004
79153
|
}));
|
|
79005
79154
|
}
|
|
@@ -79022,14 +79171,14 @@ function registryRecordToYaml(record4) {
|
|
|
79022
79171
|
}
|
|
79023
79172
|
return output;
|
|
79024
79173
|
}
|
|
79025
|
-
var
|
|
79174
|
+
var import_yaml16, SOURCE_NAME_PATTERN2, REPO_DATE_NAMESPACE_PATTERN2;
|
|
79026
79175
|
var init_repoSourceRegistry = __esm(() => {
|
|
79027
79176
|
init_src2();
|
|
79028
79177
|
init_cliFeedback();
|
|
79029
79178
|
init_errors3();
|
|
79030
79179
|
init_exitCode();
|
|
79031
79180
|
init_atomicWrite();
|
|
79032
|
-
|
|
79181
|
+
import_yaml16 = __toESM(require_dist(), 1);
|
|
79033
79182
|
SOURCE_NAME_PATTERN2 = /^[a-z0-9][a-z0-9._-]*$/u;
|
|
79034
79183
|
REPO_DATE_NAMESPACE_PATTERN2 = /^\d{8}$/u;
|
|
79035
79184
|
});
|
|
@@ -80240,7 +80389,7 @@ async function readProductionSubmission(input) {
|
|
|
80240
80389
|
throw invalidFile(input.path, "Manifest exceeds its transport budget.");
|
|
80241
80390
|
let value;
|
|
80242
80391
|
try {
|
|
80243
|
-
value = productionSubmissionSchema.parse(
|
|
80392
|
+
value = productionSubmissionSchema.parse(import_yaml17.default.parse(manifest.text));
|
|
80244
80393
|
} catch (error) {
|
|
80245
80394
|
throw invalidFile(input.path, `Invalid submission manifest: ${error instanceof Error ? error.message : String(error)}`);
|
|
80246
80395
|
}
|
|
@@ -80286,7 +80435,7 @@ async function readProductionSubmission(input) {
|
|
|
80286
80435
|
}
|
|
80287
80436
|
return { stage: value.stage, tasks: fixed, bytes };
|
|
80288
80437
|
}
|
|
80289
|
-
var
|
|
80438
|
+
var import_yaml17, localId, filePath, productionSubmissionSchema, DEFAULT_LIMITS;
|
|
80290
80439
|
var init_productionSubmissionFiles = __esm(() => {
|
|
80291
80440
|
init_zod();
|
|
80292
80441
|
init_errors3();
|
|
@@ -80294,7 +80443,7 @@ var init_productionSubmissionFiles = __esm(() => {
|
|
|
80294
80443
|
init_exitCode();
|
|
80295
80444
|
init_durableSingleFileTransaction();
|
|
80296
80445
|
init_durableMultiFileTransaction();
|
|
80297
|
-
|
|
80446
|
+
import_yaml17 = __toESM(require_dist(), 1);
|
|
80298
80447
|
localId = exports_external.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/u);
|
|
80299
80448
|
filePath = exports_external.string().min(1);
|
|
80300
80449
|
productionSubmissionSchema = exports_external.object({
|
|
@@ -80318,7 +80467,7 @@ import { readFile as readFile26 } from "node:fs/promises";
|
|
|
80318
80467
|
import { join as join29 } from "node:path";
|
|
80319
80468
|
function emptyEdits(text5) {
|
|
80320
80469
|
try {
|
|
80321
|
-
const value =
|
|
80470
|
+
const value = import_yaml18.default.parse(text5);
|
|
80322
80471
|
return Array.isArray(value?.edits) && value.edits.length === 0 && Object.keys(value).length === 1;
|
|
80323
80472
|
} catch {
|
|
80324
80473
|
return false;
|
|
@@ -80349,11 +80498,11 @@ async function previousProductionDrafts(root, stage, tasks = stage.tasks) {
|
|
|
80349
80498
|
}
|
|
80350
80499
|
return result;
|
|
80351
80500
|
}
|
|
80352
|
-
var
|
|
80501
|
+
var import_yaml18;
|
|
80353
80502
|
var init_productionDraftMigration = __esm(() => {
|
|
80354
80503
|
init_productionSubmissionFiles();
|
|
80355
80504
|
init_durableMultiFileTransaction();
|
|
80356
|
-
|
|
80505
|
+
import_yaml18 = __toESM(require_dist(), 1);
|
|
80357
80506
|
});
|
|
80358
80507
|
|
|
80359
80508
|
// src/project/lifecyclePaths.ts
|
|
@@ -80612,7 +80761,7 @@ function parseFrontmatter2(content3) {
|
|
|
80612
80761
|
if (match?.[1] === undefined)
|
|
80613
80762
|
return;
|
|
80614
80763
|
try {
|
|
80615
|
-
const parsed =
|
|
80764
|
+
const parsed = import_yaml19.default.parse(match[1]);
|
|
80616
80765
|
if (!isRecord8(parsed))
|
|
80617
80766
|
return;
|
|
80618
80767
|
return { record: parsed, body: content3.slice(match[0].length) };
|
|
@@ -80666,7 +80815,7 @@ function hydrateApprovedKnowledgeMarkdown(input) {
|
|
|
80666
80815
|
return input.content;
|
|
80667
80816
|
}
|
|
80668
80817
|
return `---
|
|
80669
|
-
${
|
|
80818
|
+
${import_yaml19.default.stringify(frontmatter).trimEnd()}
|
|
80670
80819
|
---
|
|
80671
80820
|
${parsed.body}`;
|
|
80672
80821
|
}
|
|
@@ -80681,7 +80830,7 @@ function compactApprovedKnowledgeMarkdown(content3) {
|
|
|
80681
80830
|
...typeof compact.title === "string" ? { title: compact.title } : {}
|
|
80682
80831
|
});
|
|
80683
80832
|
return `---
|
|
80684
|
-
${
|
|
80833
|
+
${import_yaml19.default.stringify(compact).trimEnd()}
|
|
80685
80834
|
---
|
|
80686
80835
|
${parsed.body}`;
|
|
80687
80836
|
}
|
|
@@ -80699,17 +80848,17 @@ function ensureApprovedKnowledgePresentation(content3) {
|
|
|
80699
80848
|
if (parsed.record.description === description && parsed.body === body)
|
|
80700
80849
|
return content3;
|
|
80701
80850
|
return `---
|
|
80702
|
-
${
|
|
80851
|
+
${import_yaml19.default.stringify({ ...parsed.record, description }).trimEnd()}
|
|
80703
80852
|
---
|
|
80704
80853
|
${body}`;
|
|
80705
80854
|
}
|
|
80706
|
-
var
|
|
80855
|
+
var import_yaml19, STRUCTURE_PATH, FRONTMATTER_RE2, COMPACT_FIELDS;
|
|
80707
80856
|
var init_approvedKnowledgeMetadata = __esm(() => {
|
|
80708
80857
|
init_approvedFileRead();
|
|
80709
80858
|
init_commandReadCache();
|
|
80710
80859
|
init_src2();
|
|
80711
80860
|
init_packageKnowledgeProjection();
|
|
80712
|
-
|
|
80861
|
+
import_yaml19 = __toESM(require_dist(), 1);
|
|
80713
80862
|
STRUCTURE_PATH = join32("knowledge", "structure.yaml");
|
|
80714
80863
|
FRONTMATTER_RE2 = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;
|
|
80715
80864
|
COMPACT_FIELDS = new Set([
|
|
@@ -80783,65 +80932,6 @@ var init_productionArticleTarget = __esm(() => {
|
|
|
80783
80932
|
init_durableSingleFileTransaction();
|
|
80784
80933
|
});
|
|
80785
80934
|
|
|
80786
|
-
// src/project/productionFeedback.ts
|
|
80787
|
-
var exports_productionFeedback = {};
|
|
80788
|
-
__export(exports_productionFeedback, {
|
|
80789
|
-
withProductionFeedback: () => withProductionFeedback,
|
|
80790
|
-
SubmissionInputErrors: () => SubmissionInputErrors,
|
|
80791
|
-
SubmissionInputError: () => SubmissionInputError
|
|
80792
|
-
});
|
|
80793
|
-
async function withProductionFeedback(input, run) {
|
|
80794
|
-
try {
|
|
80795
|
-
return await run();
|
|
80796
|
-
} catch (error) {
|
|
80797
|
-
const schemaError2 = error instanceof ZodError;
|
|
80798
|
-
const inputError = error instanceof SubmissionInputError;
|
|
80799
|
-
const syntaxError = error instanceof import_yaml19.YAMLParseError;
|
|
80800
|
-
const existing = error instanceof ContextError ? error : undefined;
|
|
80801
|
-
const ioCode = error?.code;
|
|
80802
|
-
const detail = {
|
|
80803
|
-
category: schemaError2 || syntaxError || inputError ? ErrorCategory.UserInputInvalid : ErrorCategory.WorkspaceStateInvalid,
|
|
80804
|
-
reason_code: `production-${input.operation}-failed`,
|
|
80805
|
-
next_action: { command: "context status --format json", ...input.recovery ? { instruction: input.recovery } : inputError ? { instruction: "Correct the reported item in the input file and resubmit it with the same revision." } : {} },
|
|
80806
|
-
...input.file ? { file: input.file } : {},
|
|
80807
|
-
...schemaError2 ? { issues: error.issues.map((issue) => ({ path: issue.path, message: issue.message })) } : {},
|
|
80808
|
-
...inputError ? { issues: [{ path: error.path, message: error.message }], ...error.reason ? { reason_code: error.reason } : {} } : {},
|
|
80809
|
-
...syntaxError && error.linePos ? { location: error.linePos } : {},
|
|
80810
|
-
...typeof ioCode === "string" ? { io_code: ioCode } : {},
|
|
80811
|
-
...existing?.detail
|
|
80812
|
-
};
|
|
80813
|
-
if (input.schema && detail.input_schema === undefined) {
|
|
80814
|
-
detail.input_schema = zodToJsonSchema(input.schema, { $refStrategy: "none" });
|
|
80815
|
-
}
|
|
80816
|
-
throw new ContextError(existing?.code ?? (schemaError2 || syntaxError || inputError ? ExitCode.UserError : ExitCode.WorkspaceStateError), error instanceof Error ? error.message : String(error), detail);
|
|
80817
|
-
}
|
|
80818
|
-
}
|
|
80819
|
-
var import_yaml19, SubmissionInputError, SubmissionInputErrors;
|
|
80820
|
-
var init_productionFeedback = __esm(() => {
|
|
80821
|
-
init_zod();
|
|
80822
|
-
init_esm();
|
|
80823
|
-
init_errors3();
|
|
80824
|
-
init_cliFeedback();
|
|
80825
|
-
init_exitCode();
|
|
80826
|
-
import_yaml19 = __toESM(require_dist(), 1);
|
|
80827
|
-
SubmissionInputError = class SubmissionInputError extends TypeError {
|
|
80828
|
-
path;
|
|
80829
|
-
reason;
|
|
80830
|
-
constructor(message, path2 = [], reason) {
|
|
80831
|
-
super(message);
|
|
80832
|
-
this.path = path2;
|
|
80833
|
-
this.reason = reason;
|
|
80834
|
-
}
|
|
80835
|
-
};
|
|
80836
|
-
SubmissionInputErrors = class SubmissionInputErrors extends SubmissionInputError {
|
|
80837
|
-
errors;
|
|
80838
|
-
constructor(errors4) {
|
|
80839
|
-
super(`${errors4.length} problems: ${errors4.map((error, index2) => `(${index2 + 1}) ${error.message}`).join(" ")}`, errors4[0]?.path ?? [], errors4[0]?.reason);
|
|
80840
|
-
this.errors = errors4;
|
|
80841
|
-
}
|
|
80842
|
-
};
|
|
80843
|
-
});
|
|
80844
|
-
|
|
80845
80935
|
// src/project/productionStage.ts
|
|
80846
80936
|
function productionTaskInput(task) {
|
|
80847
80937
|
return indexerProtocolDigest({
|
|
@@ -81652,83 +81742,10 @@ var init_productionPlanningMaterials = __esm(() => {
|
|
|
81652
81742
|
markdownParser = unified().use(remarkParse);
|
|
81653
81743
|
});
|
|
81654
81744
|
|
|
81655
|
-
// src/project/submittedSourceLocator.ts
|
|
81656
|
-
function assertNoCaptureGap(locator, capturedText) {
|
|
81657
|
-
const lines = capturedText.replace(/\r\n/gu, `
|
|
81658
|
-
`).split(`
|
|
81659
|
-
`).slice(locator.start_line - 1, locator.end_line);
|
|
81660
|
-
const gapOnly = (line) => CAPTURE_GAP.test(line) && line.replace(new RegExp(CAPTURE_GAP.source, "gu"), "").replace(/<br\s*\/?>|[|>\s]/giu, "") === "";
|
|
81661
|
-
const gap = lines.findIndex(gapOnly);
|
|
81662
|
-
if (gap >= 0)
|
|
81663
|
-
throw new SubmissionInputError(`${locator.path}:${locator.start_line + gap} is a capture gap (the resource was not captured), ` + "not evidence. Cite only captured lines; the missing content cannot support a claim until it is captured.");
|
|
81664
|
-
}
|
|
81665
|
-
function resolveSubmittedSourceLocator(input, capturedText) {
|
|
81666
|
-
const locator = submittedSourceLocatorSchema.parse(input);
|
|
81667
|
-
if ("start_line" in locator)
|
|
81668
|
-
return locator;
|
|
81669
|
-
const text5 = capturedText.replace(/\r\n/gu, `
|
|
81670
|
-
`);
|
|
81671
|
-
const lines = text5.split(`
|
|
81672
|
-
`);
|
|
81673
|
-
const matches = [];
|
|
81674
|
-
if ("quote" in locator) {
|
|
81675
|
-
const quote2 = locator.quote.replace(/\r\n/gu, `
|
|
81676
|
-
`);
|
|
81677
|
-
for (let offset2 = text5.indexOf(quote2);offset2 >= 0; offset2 = text5.indexOf(quote2, offset2 + 1)) {
|
|
81678
|
-
matches.push({
|
|
81679
|
-
start_line: text5.slice(0, offset2).split(`
|
|
81680
|
-
`).length,
|
|
81681
|
-
end_line: text5.slice(0, offset2 + quote2.length - 1).split(`
|
|
81682
|
-
`).length
|
|
81683
|
-
});
|
|
81684
|
-
}
|
|
81685
|
-
} else {
|
|
81686
|
-
if (!/\.(?:md|markdown|mdx)$/iu.test(locator.path))
|
|
81687
|
-
throw new SubmissionInputError("heading requires a Markdown source; use quote or start_line/end_line instead.");
|
|
81688
|
-
const marked = /^(#{1,6})[ \t]+(.+)$/u.exec(locator.heading.trim());
|
|
81689
|
-
const wanted = { level: marked?.[1].length, title: (marked?.[2] ?? locator.heading).trim() };
|
|
81690
|
-
const headings = [];
|
|
81691
|
-
let fence;
|
|
81692
|
-
for (const [index2, line] of lines.entries()) {
|
|
81693
|
-
const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(line);
|
|
81694
|
-
if (fence) {
|
|
81695
|
-
if (marker && marker[1][0] === fence.character && marker[1].length >= fence.length && !marker[2].trim())
|
|
81696
|
-
fence = undefined;
|
|
81697
|
-
continue;
|
|
81698
|
-
}
|
|
81699
|
-
if (marker) {
|
|
81700
|
-
fence = { character: marker[1][0], length: marker[1].length };
|
|
81701
|
-
continue;
|
|
81702
|
-
}
|
|
81703
|
-
const match = /^ {0,3}(#{1,6})(?:[ \t]+(.*)|[ \t]*)$/u.exec(line);
|
|
81704
|
-
if (match)
|
|
81705
|
-
headings.push({ line: index2 + 1, level: match[1].length, title: (match[2] ?? "").replace(/[ \t]+#+[ \t]*$/u, "").trim() });
|
|
81706
|
-
}
|
|
81707
|
-
for (const [index2, heading] of headings.entries()) {
|
|
81708
|
-
if (heading.title !== wanted.title || wanted.level !== undefined && heading.level !== wanted.level)
|
|
81709
|
-
continue;
|
|
81710
|
-
let end = (headings.slice(index2 + 1).find((next) => next.level <= heading.level)?.line ?? lines.length + 1) - 1;
|
|
81711
|
-
while (end > heading.line && !lines[end - 1].trim())
|
|
81712
|
-
end--;
|
|
81713
|
-
matches.push({ start_line: heading.line, end_line: end });
|
|
81714
|
-
}
|
|
81715
|
-
}
|
|
81716
|
-
if (matches.length !== 1)
|
|
81717
|
-
throw new SubmissionInputError(`Source locator matched ${matches.length} regions in ${locator.path}; candidates: ${matches.slice(0, 5).map((m) => `${m.start_line}-${m.end_line}`).join(", ") || "none"}. Use a unique heading/quote or explicit start_line/end_line.`);
|
|
81718
|
-
return articleSourceLocatorSchema.parse({ path: locator.path, ...matches[0] });
|
|
81719
|
-
}
|
|
81720
|
-
var submittedSourceLocatorSchema, CAPTURE_GAP;
|
|
81721
|
-
var init_submittedSourceLocator = __esm(() => {
|
|
81722
|
-
init_src2();
|
|
81723
|
-
init_productionFeedback();
|
|
81724
|
-
submittedSourceLocatorSchema = articleSourceLocatorInputSchema;
|
|
81725
|
-
CAPTURE_GAP = /(?:> ?)?Resource unavailable: .+? \([^;()]+; [^()]+\)\. <!-- [^>]+ -->/u;
|
|
81726
|
-
});
|
|
81727
|
-
|
|
81728
81745
|
// src/project/approvedRevisionReferences.ts
|
|
81729
81746
|
async function resolveSubmittedReference(context, id3, at2, reference2) {
|
|
81730
81747
|
if (!context.inScope(reference2.source_ref))
|
|
81731
|
-
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");
|
|
81748
|
+
throw new SubmissionInputError(`Fragment ${id3} cites ${reference2.source_ref}, which is outside this revision; allowed sources: ${context.sourceRefs.join(", ")}. ` + (citesScope(context.processedScopes, reference2.source_ref) ? "It belongs to the source update this page comes from, but not to this page: run context task adjust for this revision with that scope (in a later source update, list it in the page decision's supporting_sources instead)." : "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");
|
|
81732
81749
|
const submitted = reference2.locator;
|
|
81733
81750
|
const previous2 = context.previous.find((section) => section.id === id3)?.references ?? [];
|
|
81734
81751
|
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;
|
|
@@ -81736,7 +81753,19 @@ async function resolveSubmittedReference(context, id3, at2, reference2) {
|
|
|
81736
81753
|
const observed = await relocateUnchangedReference(context.projectRoot, context.readSource, kept);
|
|
81737
81754
|
if (observed.state === "current" || observed.state === "moved")
|
|
81738
81755
|
return observed.reference;
|
|
81739
|
-
|
|
81756
|
+
const cited = `Fragment ${id3}: ${reference2.source_ref} ${kept.locator.path}:${kept.locator.start_line}-${kept.locator.end_line} ` + "repeats an earlier citation's line numbers, so it keeps that citation's text";
|
|
81757
|
+
const current3 = observed.state === "unavailable" ? undefined : await context.readSource(reference2.source_ref, kept.locator.path, true).catch(() => {
|
|
81758
|
+
return;
|
|
81759
|
+
});
|
|
81760
|
+
if (current3 === undefined)
|
|
81761
|
+
throw new SubmissionInputError(`${cited}, but the current source cannot be read` + ` (${observed.reason ?? "source-unavailable"}). Restore or refresh the source and submit again; another locator does not help while it is unreadable.`, [...at2, "locator"], "kept-reference-unresolved");
|
|
81762
|
+
const lines = current3.replace(/\r\n/gu, `
|
|
81763
|
+
`).split(`
|
|
81764
|
+
`).length;
|
|
81765
|
+
if (kept.locator.end_line > lines)
|
|
81766
|
+
throw new SubmissionInputError(`${cited}, which is ${observed.state} in the current source; ` + `the file now has ${lines} lines, so these lines no longer exist. Cite the earlier evidence at its current position, or cite current text with a quote or heading locator.`, [...at2, "locator"], "kept-reference-unresolved");
|
|
81767
|
+
const quote2 = exactQuoteLocator(kept.locator, current3, 2000);
|
|
81768
|
+
throw new SubmissionInputError(`${cited}, which is ${observed.state} in the current source; ` + "the text now at these lines is different. To keep the earlier evidence, cite its current position. To cite the text now at these lines " + (quote2 ? `(it may be the correct new content), submit this locator instead: ${JSON.stringify(quote2)}.` : "(it may be the correct new content), use a quote or heading locator."), [...at2, "locator"], "kept-reference-unresolved");
|
|
81740
81769
|
}
|
|
81741
81770
|
const text5 = await context.readSource(reference2.source_ref, reference2.locator.path, true);
|
|
81742
81771
|
let locator;
|
|
@@ -81777,6 +81806,7 @@ async function prepareRevisionReferences(input) {
|
|
|
81777
81806
|
remember: input.remember !== false,
|
|
81778
81807
|
previous: input.previous,
|
|
81779
81808
|
sourceRefs: input.sourceRefs,
|
|
81809
|
+
processedScopes: input.processedScopes ?? [],
|
|
81780
81810
|
inScope,
|
|
81781
81811
|
readSource: Object.assign(async (source2, path2) => {
|
|
81782
81812
|
if (!inScope(source2))
|
|
@@ -86148,6 +86178,7 @@ function materializationItem(resource) {
|
|
|
86148
86178
|
};
|
|
86149
86179
|
}
|
|
86150
86180
|
function createLarkCaptureReport(input) {
|
|
86181
|
+
const budgetExceeded = input.resourceMaterialization.items.some((item) => item.reason_code === "image-budget-exceeded");
|
|
86151
86182
|
const descriptors = new Map(input.resources.map((resource) => [resourceKey2(resource), resource]));
|
|
86152
86183
|
return {
|
|
86153
86184
|
schema_version: LARK_CAPTURE_REPORT_SCHEMA_VERSION,
|
|
@@ -86161,9 +86192,22 @@ function createLarkCaptureReport(input) {
|
|
|
86161
86192
|
attributes: descriptor?.attributes ?? {}
|
|
86162
86193
|
};
|
|
86163
86194
|
}),
|
|
86164
|
-
...input.access === undefined ? {} : { access: input.access }
|
|
86195
|
+
...input.access === undefined ? {} : { access: input.access },
|
|
86196
|
+
...budgetExceeded && input.resourceBudget !== undefined ? { resource_budget: {
|
|
86197
|
+
maxBytesPerResource: input.resourceBudget.maxBytesPerResource,
|
|
86198
|
+
maxTotalBytes: input.resourceBudget.maxTotalBytes
|
|
86199
|
+
} } : {}
|
|
86165
86200
|
};
|
|
86166
86201
|
}
|
|
86202
|
+
function parseResourceBudget(value) {
|
|
86203
|
+
if (value === undefined)
|
|
86204
|
+
return;
|
|
86205
|
+
const positive = (field) => typeof field === "number" && Number.isSafeInteger(field) && field > 0;
|
|
86206
|
+
if (!isRecord10(value) || !positive(value.maxBytesPerResource) || !positive(value.maxTotalBytes)) {
|
|
86207
|
+
throw new TypeError("Lark capture report resource_budget must hold positive maxBytesPerResource and maxTotalBytes");
|
|
86208
|
+
}
|
|
86209
|
+
return { maxBytesPerResource: value.maxBytesPerResource, maxTotalBytes: value.maxTotalBytes };
|
|
86210
|
+
}
|
|
86167
86211
|
function parseAccess(value) {
|
|
86168
86212
|
if (value === undefined)
|
|
86169
86213
|
return;
|
|
@@ -86227,6 +86271,7 @@ function parseLarkCaptureReport(value) {
|
|
|
86227
86271
|
throw new TypeError("Lark capture report resource_materialization is required");
|
|
86228
86272
|
}
|
|
86229
86273
|
const access4 = parseAccess(value.access);
|
|
86274
|
+
const resourceBudget = parseResourceBudget(value.resource_budget);
|
|
86230
86275
|
return {
|
|
86231
86276
|
schema_version: LARK_CAPTURE_REPORT_SCHEMA_VERSION,
|
|
86232
86277
|
fidelity,
|
|
@@ -86236,7 +86281,8 @@ function parseLarkCaptureReport(value) {
|
|
|
86236
86281
|
...enriched[index2]?.title === undefined ? {} : { title: enriched[index2].title },
|
|
86237
86282
|
attributes: enriched[index2]?.attributes ?? {}
|
|
86238
86283
|
})),
|
|
86239
|
-
...access4 === undefined ? {} : { access: access4 }
|
|
86284
|
+
...access4 === undefined ? {} : { access: access4 },
|
|
86285
|
+
...resourceBudget === undefined ? {} : { resource_budget: resourceBudget }
|
|
86240
86286
|
};
|
|
86241
86287
|
}
|
|
86242
86288
|
function captureReportMaterialization(report) {
|
|
@@ -107949,8 +107995,10 @@ var init_larkDocxXml = __esm(() => {
|
|
|
107949
107995
|
});
|
|
107950
107996
|
|
|
107951
107997
|
// src/lib/larkResourceScheduler.ts
|
|
107998
|
+
import { readdir as readdir26, rm as rm27 } from "node:fs/promises";
|
|
107999
|
+
import { join as join117 } from "node:path";
|
|
107952
108000
|
import { setTimeout as delay } from "node:timers/promises";
|
|
107953
|
-
function
|
|
108001
|
+
function structured(value, match, depth = 0) {
|
|
107954
108002
|
if (depth > 6 || value === null)
|
|
107955
108003
|
return false;
|
|
107956
108004
|
if (typeof value === "string") {
|
|
@@ -107958,7 +108006,7 @@ function throttle(value, depth = 0) {
|
|
|
107958
108006
|
if (start2 < 0)
|
|
107959
108007
|
return false;
|
|
107960
108008
|
try {
|
|
107961
|
-
return
|
|
108009
|
+
return structured(JSON.parse(value.slice(start2)), match, depth + 1);
|
|
107962
108010
|
} catch {
|
|
107963
108011
|
return false;
|
|
107964
108012
|
}
|
|
@@ -107966,9 +108014,35 @@ function throttle(value, depth = 0) {
|
|
|
107966
108014
|
if (typeof value !== "object")
|
|
107967
108015
|
return false;
|
|
107968
108016
|
const record4 = value;
|
|
107969
|
-
if (
|
|
108017
|
+
if (match(record4))
|
|
108018
|
+
return true;
|
|
108019
|
+
return [record4.error, record4.message, record4.cause].some((entry) => structured(entry, match, depth + 1));
|
|
108020
|
+
}
|
|
108021
|
+
function failureText(result) {
|
|
108022
|
+
if (result.exitCode !== 0)
|
|
108023
|
+
return `${result.stderr}
|
|
108024
|
+
${result.stdout}`;
|
|
108025
|
+
const trimmed = result.stdout.trim();
|
|
108026
|
+
if (!trimmed.startsWith("{"))
|
|
108027
|
+
return;
|
|
108028
|
+
try {
|
|
108029
|
+
const envelope = JSON.parse(trimmed);
|
|
108030
|
+
return envelope?.ok === false ? JSON.stringify(envelope.error ?? envelope) : undefined;
|
|
108031
|
+
} catch {
|
|
108032
|
+
return;
|
|
108033
|
+
}
|
|
108034
|
+
}
|
|
108035
|
+
function isLarkResourceTransient(result) {
|
|
108036
|
+
if (result.exitCode === null)
|
|
107970
108037
|
return true;
|
|
107971
|
-
|
|
108038
|
+
const text12 = failureText(result);
|
|
108039
|
+
if (text12 === undefined || isLarkResourceThrottled(result))
|
|
108040
|
+
return false;
|
|
108041
|
+
if (structured(text12, (record4) => codes2(record4).some((code3) => TRANSIENT_STATUS.has(code3))))
|
|
108042
|
+
return true;
|
|
108043
|
+
if (structured(text12, (record4) => codes2(record4).some((code3) => PERMANENT_STATUS.has(code3)) || PERMANENT_TYPES.has(String(record4.type))))
|
|
108044
|
+
return false;
|
|
108045
|
+
return TRANSIENT_TEXT.test(text12);
|
|
107972
108046
|
}
|
|
107973
108047
|
function isLarkResourceThrottled(result) {
|
|
107974
108048
|
return throttle(result.stderr) || throttle(result.stdout);
|
|
@@ -107996,13 +108070,19 @@ function retryAfter(value, now2, depth = 0) {
|
|
|
107996
108070
|
const own5 = Number.isFinite(milliseconds) && milliseconds > 0 ? milliseconds : Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : typeof raw === "string" ? Math.max(0, Date.parse(raw) - now2) || 0 : 0;
|
|
107997
108071
|
return Math.max(own5, ...[record4.error, record4.cause, record4.message].map((entry) => retryAfter(entry, now2, depth + 1)));
|
|
107998
108072
|
}
|
|
108073
|
+
async function emptyDirectory(path3) {
|
|
108074
|
+
for (const entry of await readdir26(path3))
|
|
108075
|
+
await rm27(join117(path3, entry), { recursive: true, force: true });
|
|
108076
|
+
}
|
|
107999
108077
|
function createLarkResourceScheduler(runner2, options = {}) {
|
|
108000
108078
|
const now2 = options.now ?? Date.now;
|
|
108001
108079
|
const sleep2 = options.sleep ?? delay;
|
|
108080
|
+
const random = options.random ?? Math.random;
|
|
108002
108081
|
let concurrency = 4;
|
|
108003
108082
|
let active = 0;
|
|
108004
108083
|
let blockedUntil = 0;
|
|
108005
108084
|
let successes = 0;
|
|
108085
|
+
let lastTransientCut = Number.NEGATIVE_INFINITY;
|
|
108006
108086
|
let exhausted;
|
|
108007
108087
|
const waiters = [];
|
|
108008
108088
|
const wake2 = () => {
|
|
@@ -108028,33 +108108,54 @@ function createLarkResourceScheduler(runner2, options = {}) {
|
|
|
108028
108108
|
}
|
|
108029
108109
|
};
|
|
108030
108110
|
return async (args, commandOptions) => {
|
|
108031
|
-
|
|
108111
|
+
let throttled = 0;
|
|
108112
|
+
let transient = 0;
|
|
108113
|
+
for (;; ) {
|
|
108032
108114
|
if (exhausted)
|
|
108033
108115
|
return exhausted;
|
|
108034
108116
|
await acquire();
|
|
108117
|
+
let result;
|
|
108035
108118
|
try {
|
|
108036
108119
|
if (exhausted)
|
|
108037
108120
|
return exhausted;
|
|
108038
|
-
|
|
108039
|
-
|
|
108040
|
-
if (result.exitCode === 0 && ++successes >= 8) {
|
|
108041
|
-
concurrency = Math.min(4, concurrency + 1);
|
|
108042
|
-
successes = 0;
|
|
108043
|
-
}
|
|
108044
|
-
return result;
|
|
108121
|
+
if (throttled + transient > 0 && commandOptions?.scratchDirectory && commandOptions.cwd !== undefined) {
|
|
108122
|
+
await emptyDirectory(commandOptions.cwd);
|
|
108045
108123
|
}
|
|
108124
|
+
result = await runner2(args, commandOptions);
|
|
108125
|
+
} finally {
|
|
108126
|
+
active--;
|
|
108127
|
+
wake2();
|
|
108128
|
+
}
|
|
108129
|
+
if (isLarkResourceThrottled(result)) {
|
|
108046
108130
|
successes = 0;
|
|
108047
108131
|
concurrency = Math.max(1, Math.floor(concurrency / 2));
|
|
108048
|
-
const wait = Math.max(1000 * 2 **
|
|
108132
|
+
const wait = Math.max(1000 * 2 ** throttled, retryAfter(result.stderr, now2()), retryAfter(result.stdout, now2()));
|
|
108049
108133
|
blockedUntil = Math.max(blockedUntil, now2() + Math.min(wait, 30000));
|
|
108050
|
-
if (
|
|
108134
|
+
if (throttled >= 3 || wait > 30000) {
|
|
108051
108135
|
exhausted = result;
|
|
108052
108136
|
return result;
|
|
108053
108137
|
}
|
|
108054
|
-
|
|
108055
|
-
|
|
108056
|
-
|
|
108138
|
+
throttled++;
|
|
108139
|
+
continue;
|
|
108140
|
+
}
|
|
108141
|
+
if (isLarkResourceTransient(result)) {
|
|
108142
|
+
successes = 0;
|
|
108143
|
+
if (transient >= TRANSIENT_RETRIES)
|
|
108144
|
+
return result;
|
|
108145
|
+
if (now2() - lastTransientCut >= TRANSIENT_CUT_WINDOW_MS) {
|
|
108146
|
+
concurrency = Math.max(1, Math.floor(concurrency / 2));
|
|
108147
|
+
lastTransientCut = now2();
|
|
108148
|
+
}
|
|
108149
|
+
const base = 1000 * 3 ** transient;
|
|
108150
|
+
transient++;
|
|
108151
|
+
await sleep2(Math.round(base * (0.75 + random() * 0.5)));
|
|
108152
|
+
continue;
|
|
108153
|
+
}
|
|
108154
|
+
if (failureText(result) === undefined && ++successes >= 8) {
|
|
108155
|
+
concurrency = Math.min(4, concurrency + 1);
|
|
108156
|
+
successes = 0;
|
|
108057
108157
|
}
|
|
108158
|
+
return result;
|
|
108058
108159
|
}
|
|
108059
108160
|
};
|
|
108060
108161
|
}
|
|
@@ -108065,7 +108166,35 @@ async function forEachLarkResource(items, visit4) {
|
|
|
108065
108166
|
await visit4(items[next2++]);
|
|
108066
108167
|
}));
|
|
108067
108168
|
}
|
|
108068
|
-
var
|
|
108169
|
+
var throttle = (value) => structured(value, (record4) => [record4.code, record4.status, record4.status_code].some((code3) => ["429", "99991400"].includes(String(code3))) || record4.type === "rate_limit" || record4.subtype === "rate_limited"), codes2 = (record4) => [record4.code, record4.status, record4.status_code].filter((code3) => code3 !== undefined && code3 !== null).map(String), TRANSIENT_STATUS, PERMANENT_STATUS, PERMANENT_TYPES, TRANSIENT_TEXT, TRANSIENT_RETRIES = 3, TRANSIENT_CUT_WINDOW_MS = 5000;
|
|
108170
|
+
var init_larkResourceScheduler = __esm(() => {
|
|
108171
|
+
TRANSIENT_STATUS = new Set(["502", "503", "504"]);
|
|
108172
|
+
PERMANENT_STATUS = new Set(["400", "401", "403", "404", "500", "2890003", "3380004", "99991672"]);
|
|
108173
|
+
PERMANENT_TYPES = new Set(["authorization", "authentication", "validation"]);
|
|
108174
|
+
TRANSIENT_TEXT = new RegExp([
|
|
108175
|
+
String.raw`(?:HTTP[/\s\d.]*\s|status(?:[ _]code)?[:=\s]+|code[:=\s]+)(?:502|503|504)\b`,
|
|
108176
|
+
String.raw`\b(?:502|503|504)\s+(?:bad gateway|service unavailable|gateway time-?out)`,
|
|
108177
|
+
"bad gateway",
|
|
108178
|
+
"service unavailable",
|
|
108179
|
+
"gateway time-?out",
|
|
108180
|
+
"request time-?out",
|
|
108181
|
+
"timed out",
|
|
108182
|
+
"deadline exceeded",
|
|
108183
|
+
"i/o timeout",
|
|
108184
|
+
String.raw`client\.timeout`,
|
|
108185
|
+
"timeout exceeded",
|
|
108186
|
+
"ETIMEDOUT",
|
|
108187
|
+
"ECONNRESET",
|
|
108188
|
+
"ECONNABORTED",
|
|
108189
|
+
"EPIPE",
|
|
108190
|
+
"EAI_AGAIN",
|
|
108191
|
+
"connection (?:reset|refused|closed)",
|
|
108192
|
+
"socket hang up",
|
|
108193
|
+
"unexpected EOF",
|
|
108194
|
+
"network is unreachable",
|
|
108195
|
+
"TLS handshake timeout"
|
|
108196
|
+
].join("|"), "iu");
|
|
108197
|
+
});
|
|
108069
108198
|
|
|
108070
108199
|
// src/lib/larkResourceCommand.ts
|
|
108071
108200
|
function hasMissingScope(value, depth = 0) {
|
|
@@ -108177,19 +108306,20 @@ var init_larkResourceCommand = __esm(() => {
|
|
|
108177
108306
|
});
|
|
108178
108307
|
|
|
108179
108308
|
// src/lib/larkMediaDownload.ts
|
|
108180
|
-
import { readdir as
|
|
108181
|
-
import { join as
|
|
108309
|
+
import { readdir as readdir27, rm as rm28 } from "node:fs/promises";
|
|
108310
|
+
import { join as join118 } from "node:path";
|
|
108182
108311
|
async function downloadLarkMedia(input) {
|
|
108312
|
+
const options = { cwd: input.cwd, scratchDirectory: true, ...input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs } };
|
|
108183
108313
|
const shared = ["--as", input.identity, "--token", input.token, "--output", "./resource", "--format", "json"];
|
|
108184
108314
|
try {
|
|
108185
|
-
await runLarkResourceCommand(input.runner, ["docs", "+media-download", ...shared, "--type", input.type, "--overwrite"],
|
|
108315
|
+
await runLarkResourceCommand(input.runner, ["docs", "+media-download", ...shared, "--type", input.type, "--overwrite"], options);
|
|
108186
108316
|
return "original";
|
|
108187
108317
|
} catch (error) {
|
|
108188
108318
|
if (!input.allowPreview || !isLarkResourcePermissionDenied(error))
|
|
108189
108319
|
throw error;
|
|
108190
|
-
for (const entry of await
|
|
108191
|
-
await
|
|
108192
|
-
await runLarkResourceCommand(input.runner, ["docs", "+media-preview", ...shared],
|
|
108320
|
+
for (const entry of await readdir27(input.cwd))
|
|
108321
|
+
await rm28(join118(input.cwd, entry), { recursive: true, force: true });
|
|
108322
|
+
await runLarkResourceCommand(input.runner, ["docs", "+media-preview", ...shared], options);
|
|
108193
108323
|
return "preview";
|
|
108194
108324
|
}
|
|
108195
108325
|
}
|
|
@@ -108198,9 +108328,9 @@ var init_larkMediaDownload = __esm(() => {
|
|
|
108198
108328
|
});
|
|
108199
108329
|
|
|
108200
108330
|
// src/lib/larkWhiteboardExport.ts
|
|
108201
|
-
import { mkdtemp as mkdtemp5, readFile as readFile95, rm as
|
|
108331
|
+
import { mkdtemp as mkdtemp5, readFile as readFile95, rm as rm29 } from "node:fs/promises";
|
|
108202
108332
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
108203
|
-
import { join as
|
|
108333
|
+
import { join as join119 } from "node:path";
|
|
108204
108334
|
function stableJson2(value) {
|
|
108205
108335
|
if (value === undefined)
|
|
108206
108336
|
return "null";
|
|
@@ -108230,7 +108360,7 @@ function canonicalWhiteboardPayload(value) {
|
|
|
108230
108360
|
};
|
|
108231
108361
|
}
|
|
108232
108362
|
async function exportLarkWhiteboardRaw(runner2, identity2, token) {
|
|
108233
|
-
const tempRoot = await mkdtemp5(
|
|
108363
|
+
const tempRoot = await mkdtemp5(join119(tmpdir2(), "context-lark-whiteboard-"));
|
|
108234
108364
|
try {
|
|
108235
108365
|
await runLarkResourceCommand(runner2, [
|
|
108236
108366
|
"whiteboard",
|
|
@@ -108246,12 +108376,12 @@ async function exportLarkWhiteboardRaw(runner2, identity2, token) {
|
|
|
108246
108376
|
"--overwrite",
|
|
108247
108377
|
"--format",
|
|
108248
108378
|
"json"
|
|
108249
|
-
], { cwd: tempRoot });
|
|
108250
|
-
const rawPayload = JSON.parse(await readFile95(
|
|
108379
|
+
], { cwd: tempRoot, scratchDirectory: true });
|
|
108380
|
+
const rawPayload = JSON.parse(await readFile95(join119(tempRoot, "raw.json"), "utf8"));
|
|
108251
108381
|
return Buffer.from(`${stableJson2(canonicalWhiteboardPayload(rawPayload))}
|
|
108252
108382
|
`, "utf8");
|
|
108253
108383
|
} finally {
|
|
108254
|
-
await
|
|
108384
|
+
await rm29(tempRoot, { recursive: true, force: true });
|
|
108255
108385
|
}
|
|
108256
108386
|
}
|
|
108257
108387
|
var init_larkWhiteboardExport = __esm(() => {
|
|
@@ -108278,16 +108408,39 @@ function omitLarkImage(resource, policy, items, replacements, mediaType, failure
|
|
|
108278
108408
|
});
|
|
108279
108409
|
return true;
|
|
108280
108410
|
}
|
|
108281
|
-
|
|
108411
|
+
function omitLarkResourceByPolicy(resource, policy, items, replacements) {
|
|
108412
|
+
const excluded = resource.kind === "file" ? policy.files === "reference-only" : (resource.kind === "whiteboard" || resource.kind === "diagram" && resource.inline_content !== true) && policy.whiteboards === "reference-only";
|
|
108413
|
+
if (!excluded)
|
|
108414
|
+
return false;
|
|
108415
|
+
const label2 = resource.kind === "file" ? "File" : resource.kind === "diagram" ? "Diagram" : "Whiteboard";
|
|
108416
|
+
const title2 = (resource.title ?? label2.toLowerCase()).replace(/[\r\n<>]/gu, " ");
|
|
108417
|
+
replacements.set(resource.locator, `> ${label2} omitted: ${title2}. Excluded by selected policy. See the source document. <!-- ${resource.locator} -->`);
|
|
108418
|
+
items.push({
|
|
108419
|
+
kind: resource.kind,
|
|
108420
|
+
locator: resource.locator,
|
|
108421
|
+
status: "reference-only",
|
|
108422
|
+
required: false,
|
|
108423
|
+
asset_paths: [],
|
|
108424
|
+
reason_code: resource.kind === "file" ? "file-excluded-by-policy" : "whiteboard-excluded-by-policy",
|
|
108425
|
+
reason: `${label2} bytes were not retained; the selected resource policy preserves a placeholder and source reference`
|
|
108426
|
+
});
|
|
108427
|
+
return true;
|
|
108428
|
+
}
|
|
108429
|
+
var LarkResourceBudgetError, LARK_POLICY_EXCLUSION_REASON_CODES;
|
|
108282
108430
|
var init_larkImagePolicy = __esm(() => {
|
|
108283
108431
|
LarkResourceBudgetError = class LarkResourceBudgetError extends Error {
|
|
108284
108432
|
};
|
|
108433
|
+
LARK_POLICY_EXCLUSION_REASON_CODES = new Set([
|
|
108434
|
+
"image-excluded-by-policy",
|
|
108435
|
+
"file-excluded-by-policy",
|
|
108436
|
+
"whiteboard-excluded-by-policy"
|
|
108437
|
+
]);
|
|
108285
108438
|
});
|
|
108286
108439
|
|
|
108287
108440
|
// src/lib/larkResourceMaterialization.ts
|
|
108288
108441
|
import { createHash as createHash36 } from "node:crypto";
|
|
108289
|
-
import { mkdtemp as mkdtemp6, readFile as readFile96, readdir as
|
|
108290
|
-
import { extname as extname13, join as
|
|
108442
|
+
import { mkdtemp as mkdtemp6, readFile as readFile96, readdir as readdir28, rm as rm30 } from "node:fs/promises";
|
|
108443
|
+
import { extname as extname13, join as join120 } from "node:path";
|
|
108291
108444
|
import { tmpdir as tmpdir3 } from "node:os";
|
|
108292
108445
|
function countByKind(items, status) {
|
|
108293
108446
|
const counts2 = new Map;
|
|
@@ -108395,17 +108548,17 @@ async function downloadedFile(input) {
|
|
|
108395
108548
|
const bytes = await readFile96(input.localPath);
|
|
108396
108549
|
return { path: input.localPath, bytes, mediaType: mediaTypeFor(input.localPath, bytes), representation: "original" };
|
|
108397
108550
|
}
|
|
108398
|
-
const tempRoot = await mkdtemp6(
|
|
108551
|
+
const tempRoot = await mkdtemp6(join120(tmpdir3(), "context-lark-resource-"));
|
|
108399
108552
|
try {
|
|
108400
108553
|
const representation = await downloadLarkMedia({ ...input, cwd: tempRoot });
|
|
108401
|
-
const entries2 = (await
|
|
108554
|
+
const entries2 = (await readdir28(tempRoot, { withFileTypes: true })).filter((entry) => entry.isFile());
|
|
108402
108555
|
if (entries2.length !== 1)
|
|
108403
108556
|
throw new Error(`media download produced ${entries2.length} files, expected exactly one`);
|
|
108404
108557
|
const path3 = entries2[0]?.name ?? "resource.bin";
|
|
108405
|
-
const bytes = await readFile96(
|
|
108558
|
+
const bytes = await readFile96(join120(tempRoot, path3));
|
|
108406
108559
|
return { path: path3, bytes, mediaType: mediaTypeFor(path3, bytes), representation };
|
|
108407
108560
|
} finally {
|
|
108408
|
-
await
|
|
108561
|
+
await rm30(tempRoot, { recursive: true, force: true });
|
|
108409
108562
|
}
|
|
108410
108563
|
}
|
|
108411
108564
|
function parseCsv(value) {
|
|
@@ -108474,9 +108627,9 @@ async function sheetMaterialization(resource, runner2, identity2) {
|
|
|
108474
108627
|
const sheetId = resource.attributes["sheet-id"];
|
|
108475
108628
|
if (token === undefined || sheetId === undefined)
|
|
108476
108629
|
throw new Error("embedded Sheet requires token and sheet-id");
|
|
108477
|
-
const tempRoot = await mkdtemp6(
|
|
108630
|
+
const tempRoot = await mkdtemp6(join120(tmpdir3(), "context-lark-sheet-"));
|
|
108478
108631
|
try {
|
|
108479
|
-
const outputPath =
|
|
108632
|
+
const outputPath = join120(tempRoot, "sheet.json");
|
|
108480
108633
|
const stdout = await runLarkResourceCommand(runner2, [
|
|
108481
108634
|
"sheets",
|
|
108482
108635
|
"+csv-get",
|
|
@@ -108491,7 +108644,7 @@ async function sheetMaterialization(resource, runner2, identity2) {
|
|
|
108491
108644
|
"./sheet.json",
|
|
108492
108645
|
"--format",
|
|
108493
108646
|
"json"
|
|
108494
|
-
], { cwd: tempRoot });
|
|
108647
|
+
], { cwd: tempRoot, scratchDirectory: true });
|
|
108495
108648
|
const receipt2 = jsonPayload(stdout);
|
|
108496
108649
|
if (findBooleanField(receipt2, "truncated") === true || findBooleanField(receipt2, "complete") === false) {
|
|
108497
108650
|
throw new Error("embedded Sheet read was truncated");
|
|
@@ -108518,7 +108671,7 @@ ${markdownTable2(parseCsv(csv))}
|
|
|
108518
108671
|
[CSV snapshot](${sourceAssetTarget(path3)}) <!-- ${resource.locator} -->`
|
|
108519
108672
|
};
|
|
108520
108673
|
} finally {
|
|
108521
|
-
await
|
|
108674
|
+
await rm30(tempRoot, { recursive: true, force: true });
|
|
108522
108675
|
}
|
|
108523
108676
|
}
|
|
108524
108677
|
function basePageRecords(value) {
|
|
@@ -108738,7 +108891,9 @@ function assertBudget(asset, policy, total) {
|
|
|
108738
108891
|
}
|
|
108739
108892
|
}
|
|
108740
108893
|
async function materializeLarkResources(input) {
|
|
108741
|
-
|
|
108894
|
+
const raw = input.runner;
|
|
108895
|
+
const timed = (args, options) => raw(args, { ...options, timeoutMs: options?.timeoutMs ?? RESOURCE_TIMEOUT_MS });
|
|
108896
|
+
input = { ...input, runner: createLarkResourceScheduler(timed) };
|
|
108742
108897
|
const assets = [];
|
|
108743
108898
|
const replacements = new Map;
|
|
108744
108899
|
const items = [];
|
|
@@ -108753,6 +108908,10 @@ async function materializeLarkResources(input) {
|
|
|
108753
108908
|
const required = REQUIRED_KINDS.has(resource.kind);
|
|
108754
108909
|
if (omitLarkImage(resource, input.policy, items, replacements))
|
|
108755
108910
|
return;
|
|
108911
|
+
if (omitLarkResourceByPolicy(resource, input.policy, items, replacements))
|
|
108912
|
+
return;
|
|
108913
|
+
if (resource.kind === "image" && input.budgetExcluded?.has(resource.locator) && omitLarkImage(resource, input.policy, items, replacements, undefined, "The earlier capture of this revision skipped it for exceeding the resource budget; it was not downloaded again"))
|
|
108914
|
+
return;
|
|
108756
108915
|
try {
|
|
108757
108916
|
if (resource.kind === "diagram" && resource.inline_content === true) {
|
|
108758
108917
|
replacements.set(resource.locator, "");
|
|
@@ -108809,7 +108968,7 @@ async function materializeLarkResources(input) {
|
|
|
108809
108968
|
throw new Error("synced reference nesting exceeds 4 levels");
|
|
108810
108969
|
if (input.resolveSyncedReference === undefined)
|
|
108811
108970
|
throw new Error("synced reference resolver is unavailable");
|
|
108812
|
-
const projected = await input.resolveSyncedReference(resource);
|
|
108971
|
+
const projected = await input.resolveSyncedReference(resource, input.runner);
|
|
108813
108972
|
const digest8 = resourceDigest(resource);
|
|
108814
108973
|
const asset2 = {
|
|
108815
108974
|
path: `materialized/synced-reference/${digest8}.md`,
|
|
@@ -108833,12 +108992,16 @@ async function materializeLarkResources(input) {
|
|
|
108833
108992
|
const token = resourceToken(resource);
|
|
108834
108993
|
if (token === undefined)
|
|
108835
108994
|
throw new Error(`${resource.kind} has no downloadable token`);
|
|
108836
|
-
const
|
|
108995
|
+
const preloaded = reusable.get(key);
|
|
108996
|
+
reusable.delete(key);
|
|
108997
|
+
const reused = preloaded ?? (depth > 0 && (resource.kind === "image" || resource.kind === "file") ? await input.reuse?.(resource, identity2) : undefined);
|
|
108998
|
+
const downloaded = reused ?? await downloadedFile({
|
|
108837
108999
|
runner: input.runner,
|
|
108838
109000
|
identity: identity2,
|
|
108839
109001
|
token,
|
|
108840
109002
|
type: "media",
|
|
108841
109003
|
allowPreview: resource.kind === "image",
|
|
109004
|
+
timeoutMs: resource.kind === "image" ? RESOURCE_TIMEOUT_MS : LARGE_RESOURCE_TIMEOUT_MS,
|
|
108842
109005
|
...input.mediaFiles?.[token] === undefined ? {} : { localPath: input.mediaFiles[token] }
|
|
108843
109006
|
});
|
|
108844
109007
|
if (omitLarkImage(resource, input.policy, items, replacements, downloaded.mediaType))
|
|
@@ -108887,7 +109050,20 @@ async function materializeLarkResources(input) {
|
|
|
108887
109050
|
});
|
|
108888
109051
|
}
|
|
108889
109052
|
};
|
|
108890
|
-
|
|
109053
|
+
const reusable = new Map;
|
|
109054
|
+
if (input.reuse !== undefined) {
|
|
109055
|
+
for (const resource of input.resources) {
|
|
109056
|
+
if (resource.kind === "image" ? input.policy.images === "reference-only" || input.budgetExcluded?.has(resource.locator) : resource.kind !== "file" || input.policy.files === "reference-only")
|
|
109057
|
+
continue;
|
|
109058
|
+
const found = await input.reuse(resource, identity2);
|
|
109059
|
+
if (found !== undefined)
|
|
109060
|
+
reusable.set(`${resource.kind}\x00${resource.locator}`, found);
|
|
109061
|
+
}
|
|
109062
|
+
}
|
|
109063
|
+
const leaves = input.resources.filter((resource) => resource.kind !== "synced-reference");
|
|
109064
|
+
for (const resource of leaves.filter((resource2) => reusable.has(`${resource2.kind}\x00${resource2.locator}`)))
|
|
109065
|
+
await materialize(resource, 0);
|
|
109066
|
+
await forEachLarkResource(leaves.filter((resource) => !reusable.has(`${resource.kind}\x00${resource.locator}`)), (resource) => materialize(resource, 0));
|
|
108891
109067
|
for (const resource of input.resources.filter((resource2) => resource2.kind === "synced-reference"))
|
|
108892
109068
|
await materialize(resource, 0);
|
|
108893
109069
|
items.sort((a2, b) => a2.locator.localeCompare(b.locator) || a2.kind.localeCompare(b.kind));
|
|
@@ -108917,7 +109093,7 @@ function applyLarkResourceReplacements(markdown, resources, replacements) {
|
|
|
108917
109093
|
}
|
|
108918
109094
|
return output;
|
|
108919
109095
|
}
|
|
108920
|
-
var REQUIRED_KINDS, MEDIA_TYPES_BY_EXTENSION;
|
|
109096
|
+
var RESOURCE_TIMEOUT_MS = 120000, LARGE_RESOURCE_TIMEOUT_MS = 300000, REQUIRED_KINDS, MEDIA_TYPES_BY_EXTENSION;
|
|
108921
109097
|
var init_larkResourceMaterialization = __esm(() => {
|
|
108922
109098
|
init_larkResourceScheduler();
|
|
108923
109099
|
init_larkMediaDownload();
|
|
@@ -109114,6 +109290,13 @@ var init_larkReadIdentity = __esm(() => {
|
|
|
109114
109290
|
|
|
109115
109291
|
// src/lib/feishu.ts
|
|
109116
109292
|
import { spawn as spawn6 } from "node:child_process";
|
|
109293
|
+
function sameLarkRevision(earlier, revisionId, rawContentHash) {
|
|
109294
|
+
if (earlier === undefined)
|
|
109295
|
+
return false;
|
|
109296
|
+
if (revisionId !== undefined || earlier.revisionId !== undefined)
|
|
109297
|
+
return revisionId === earlier.revisionId;
|
|
109298
|
+
return rawContentHash !== undefined && rawContentHash === earlier.rawContentHash;
|
|
109299
|
+
}
|
|
109117
109300
|
async function detectDocsFetchCapabilities(runner2) {
|
|
109118
109301
|
const result = await runner2(["docs", "+fetch", "--help"]).catch(() => ({
|
|
109119
109302
|
stdout: "",
|
|
@@ -109507,24 +109690,27 @@ async function fetchFeishuDocSnapshot(input, runner2 = defaultRunner) {
|
|
|
109507
109690
|
};
|
|
109508
109691
|
}
|
|
109509
109692
|
const resources = [...new Map([...projection?.resources ?? [], ...larkMarkdownImageResources(body2)].map((resource) => [resource.locator, resource])).values()];
|
|
109693
|
+
const policy = {
|
|
109694
|
+
...DEFAULT_RESOURCE_POLICY,
|
|
109695
|
+
...input.resourcePolicy
|
|
109696
|
+
};
|
|
109510
109697
|
if (resources.length) {
|
|
109511
|
-
const
|
|
109512
|
-
...DEFAULT_RESOURCE_POLICY,
|
|
109513
|
-
...input.resourcePolicy
|
|
109514
|
-
};
|
|
109698
|
+
const earlier = sameLarkRevision(input.reuseResources, revisionId, projection?.rawContentHash) ? input.reuseResources : undefined;
|
|
109515
109699
|
const materialized = await materializeLarkResources({
|
|
109516
109700
|
resources,
|
|
109517
109701
|
runner: runner2,
|
|
109518
109702
|
...input.prefetched?.mediaFiles === undefined ? {} : { mediaFiles: input.prefetched.mediaFiles },
|
|
109703
|
+
...earlier === undefined ? {} : { reuse: earlier.load },
|
|
109704
|
+
...earlier?.budgetExcluded?.identity === accessIdentity ? { budgetExcluded: earlier.budgetExcluded.locators } : {},
|
|
109519
109705
|
policy,
|
|
109520
109706
|
identity: accessIdentity,
|
|
109521
|
-
resolveSyncedReference: async (resource) => {
|
|
109707
|
+
resolveSyncedReference: async (resource, scheduled) => {
|
|
109522
109708
|
const sourceToken = resource.attributes["src-token"];
|
|
109523
109709
|
const blockId = resource.attributes["src-block-id"];
|
|
109524
109710
|
if (sourceToken === undefined || blockId === undefined) {
|
|
109525
109711
|
throw new LarkCliError("synced reference requires src-token and src-block-id", 0, "");
|
|
109526
109712
|
}
|
|
109527
|
-
const synced = await fetchDocsResponse({ url: sourceToken }, docsFetchPlan,
|
|
109713
|
+
const synced = await fetchDocsResponse({ url: sourceToken }, docsFetchPlan, scheduled, accessIdentity);
|
|
109528
109714
|
if (synced.contentFormat !== "xml") {
|
|
109529
109715
|
throw new LarkCliError("synced reference source did not return XML", 0, "");
|
|
109530
109716
|
}
|
|
@@ -109550,7 +109736,8 @@ async function fetchFeishuDocSnapshot(input, runner2 = defaultRunner) {
|
|
|
109550
109736
|
fidelity,
|
|
109551
109737
|
resourceMaterialization,
|
|
109552
109738
|
resources,
|
|
109553
|
-
access: access7
|
|
109739
|
+
access: access7,
|
|
109740
|
+
resourceBudget: { maxBytesPerResource: policy.maxBytesPerResource, maxTotalBytes: policy.maxTotalBytes }
|
|
109554
109741
|
}));
|
|
109555
109742
|
if (title2 !== undefined && title2.length > 0 && !/^#\s/.test(body2)) {
|
|
109556
109743
|
return {
|
|
@@ -109585,12 +109772,28 @@ async function readPrefetchedLarkDocument(url, prefetched) {
|
|
|
109585
109772
|
}, prefetched.identity);
|
|
109586
109773
|
}
|
|
109587
109774
|
var LARK_BIN = "lark-cli", MAX_FETCH_PAGES = 50, MAX_STRUCTURAL_FETCH_ATTEMPTS = 2, LarkCliNotInstalledError, LarkCliError, defaultRunner = (args, options) => new Promise((resolve8, reject) => {
|
|
109775
|
+
const timeoutMs = options?.timeoutMs;
|
|
109776
|
+
const group = timeoutMs !== undefined && process.platform !== "win32";
|
|
109588
109777
|
const child = spawn6(process.env.CONTEXT_LARK_CLI_BIN?.trim() || LARK_BIN, args, {
|
|
109589
109778
|
...options?.cwd === undefined ? {} : { cwd: options.cwd },
|
|
109779
|
+
...group ? { detached: true } : {},
|
|
109590
109780
|
stdio: ["ignore", "pipe", "pipe"]
|
|
109591
109781
|
});
|
|
109592
109782
|
let stdout = "";
|
|
109593
109783
|
let stderr = "";
|
|
109784
|
+
let timedOut = false;
|
|
109785
|
+
const timer2 = timeoutMs === undefined ? undefined : setTimeout(() => {
|
|
109786
|
+
if (child.exitCode !== null || child.signalCode !== null)
|
|
109787
|
+
return;
|
|
109788
|
+
timedOut = true;
|
|
109789
|
+
try {
|
|
109790
|
+
if (group && child.pid)
|
|
109791
|
+
process.kill(-child.pid, "SIGKILL");
|
|
109792
|
+
else
|
|
109793
|
+
child.kill("SIGKILL");
|
|
109794
|
+
} catch {}
|
|
109795
|
+
}, timeoutMs);
|
|
109796
|
+
timer2?.unref();
|
|
109594
109797
|
child.stdout.on("data", (chunk) => {
|
|
109595
109798
|
stdout += chunk.toString("utf8");
|
|
109596
109799
|
});
|
|
@@ -109598,14 +109801,23 @@ var LARK_BIN = "lark-cli", MAX_FETCH_PAGES = 50, MAX_STRUCTURAL_FETCH_ATTEMPTS =
|
|
|
109598
109801
|
stderr += chunk.toString("utf8");
|
|
109599
109802
|
});
|
|
109600
109803
|
child.on("error", (err) => {
|
|
109804
|
+
if (timer2 !== undefined)
|
|
109805
|
+
clearTimeout(timer2);
|
|
109601
109806
|
if (err.code === "ENOENT") {
|
|
109602
109807
|
reject(new LarkCliNotInstalledError);
|
|
109603
109808
|
return;
|
|
109604
109809
|
}
|
|
109605
109810
|
reject(err);
|
|
109606
109811
|
});
|
|
109812
|
+
child.on("exit", () => {
|
|
109813
|
+
if (timer2 !== undefined)
|
|
109814
|
+
clearTimeout(timer2);
|
|
109815
|
+
});
|
|
109607
109816
|
child.on("close", (code3) => {
|
|
109608
|
-
|
|
109817
|
+
if (timer2 !== undefined)
|
|
109818
|
+
clearTimeout(timer2);
|
|
109819
|
+
resolve8(timedOut ? { stdout, stderr: `${stderr}${stderr.length ? `
|
|
109820
|
+
` : ""}${LARK_BIN} ${args.slice(0, 2).join(" ")} timed out after ${Math.round(timeoutMs / 1000)} s`, exitCode: null } : { stdout, stderr, exitCode: code3 });
|
|
109609
109821
|
});
|
|
109610
109822
|
}), DEFAULT_RESOURCE_POLICY, docsFetchCapabilitiesCache;
|
|
109611
109823
|
var init_feishu = __esm(() => {
|
|
@@ -109668,13 +109880,20 @@ var init_sensitiveSourceLiteral = __esm(() => {
|
|
|
109668
109880
|
// src/project/larkSnapshotBundle.ts
|
|
109669
109881
|
import { createHash as createHash37 } from "node:crypto";
|
|
109670
109882
|
import { lstat as lstat16, mkdir as mkdir39, readFile as readFile97, realpath as realpath15, rename as rename10, writeFile as writeFile30 } from "node:fs/promises";
|
|
109671
|
-
import { basename as basename9, dirname as dirname47, isAbsolute as isAbsolute19, join as
|
|
109883
|
+
import { basename as basename9, dirname as dirname47, isAbsolute as isAbsolute19, join as join121, relative as relative31, resolve as resolve37, sep as sep10 } from "node:path";
|
|
109672
109884
|
import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
|
|
109673
109885
|
function normalizedSnapshotResourcePolicy(policy) {
|
|
109674
|
-
|
|
109886
|
+
const { files, whiteboards, ...rest } = policy;
|
|
109887
|
+
return {
|
|
109888
|
+
...rest,
|
|
109889
|
+
images: policy.images ?? "bundle",
|
|
109890
|
+
gifs: policy.gifs ?? "bundle",
|
|
109891
|
+
...files === "reference-only" ? { files } : {},
|
|
109892
|
+
...whiteboards === "reference-only" ? { whiteboards } : {}
|
|
109893
|
+
};
|
|
109675
109894
|
}
|
|
109676
109895
|
function assertSnapshotResourcePolicy(snapshot, expected) {
|
|
109677
|
-
if (!isDeepStrictEqual2(snapshot.resourcePolicy, normalizedSnapshotResourcePolicy(expected))) {
|
|
109896
|
+
if (!isDeepStrictEqual2(normalizedSnapshotResourcePolicy(snapshot.resourcePolicy), normalizedSnapshotResourcePolicy(expected))) {
|
|
109678
109897
|
throw new ContextError(ExitCode.UserError, "Saved Lark snapshot was captured with a different resource policy; import did not reinterpret or refetch its resources", {
|
|
109679
109898
|
reason_code: "lark.snapshot-policy-mismatch",
|
|
109680
109899
|
captured_policy: snapshot.resourcePolicy,
|
|
@@ -109709,7 +109928,7 @@ async function readFileEntry(root2, entry) {
|
|
|
109709
109928
|
const parts = safePath(entry.path).split("/");
|
|
109710
109929
|
let current3 = root2;
|
|
109711
109930
|
for (const [index3, part] of parts.entries()) {
|
|
109712
|
-
current3 =
|
|
109931
|
+
current3 = join121(current3, part);
|
|
109713
109932
|
const stat11 = await lstat16(current3);
|
|
109714
109933
|
if (stat11.isSymbolicLink() || (index3 === parts.length - 1 ? !stat11.isFile() : !stat11.isDirectory())) {
|
|
109715
109934
|
throw larkSnapshotError(`Snapshot entry is not a regular file: ${entry.path}`, "path-invalid");
|
|
@@ -109778,13 +109997,13 @@ async function writeLarkSnapshotBundle(input) {
|
|
|
109778
109997
|
};
|
|
109779
109998
|
schema2.parse(manifest);
|
|
109780
109999
|
for (const [path3, bytes] of files) {
|
|
109781
|
-
await mkdir39(dirname47(
|
|
109782
|
-
await writeFile30(
|
|
110000
|
+
await mkdir39(dirname47(join121(root2, path3)), { recursive: true });
|
|
110001
|
+
await writeFile30(join121(root2, path3), bytes, { flag: "wx", mode: 384 });
|
|
109783
110002
|
}
|
|
109784
110003
|
await validateBundle(root2, manifest);
|
|
109785
|
-
await writeFile30(
|
|
110004
|
+
await writeFile30(join121(root2, `${FILE2}.pending`), `${JSON.stringify(manifest, null, 2)}
|
|
109786
110005
|
`, { flag: "wx", mode: 384 });
|
|
109787
|
-
await rename10(
|
|
110006
|
+
await rename10(join121(root2, `${FILE2}.pending`), join121(root2, FILE2));
|
|
109788
110007
|
return manifest;
|
|
109789
110008
|
}
|
|
109790
110009
|
async function validateBundle(root2, manifest) {
|
|
@@ -109843,22 +110062,27 @@ async function validateBundle(root2, manifest) {
|
|
|
109843
110062
|
throw larkSnapshotError(`Resource report references a missing asset: ${path3}`);
|
|
109844
110063
|
}
|
|
109845
110064
|
}
|
|
109846
|
-
return {
|
|
109847
|
-
|
|
109848
|
-
|
|
109849
|
-
|
|
109850
|
-
|
|
109851
|
-
|
|
109852
|
-
|
|
109853
|
-
|
|
109854
|
-
|
|
109855
|
-
|
|
109856
|
-
|
|
110065
|
+
return {
|
|
110066
|
+
url: manifest.url,
|
|
110067
|
+
capturedAt: manifest.captured_at,
|
|
110068
|
+
resourcePolicy: normalizedSnapshotResourcePolicy(manifest.resource_policy),
|
|
110069
|
+
fetched: {
|
|
110070
|
+
markdown,
|
|
110071
|
+
assets,
|
|
110072
|
+
accessIdentity: manifest.access_identity,
|
|
110073
|
+
identityFallback: false,
|
|
110074
|
+
access: report.access ?? { identity: manifest.access_identity },
|
|
110075
|
+
...manifest.title === undefined ? {} : { title: manifest.title },
|
|
110076
|
+
...manifest.revision_id === undefined ? {} : { revisionId: manifest.revision_id },
|
|
110077
|
+
fidelity: report.fidelity,
|
|
110078
|
+
resourceMaterialization: { ...materialization, items: materialization.items.map((item) => ({ ...item, kind: item.kind })) }
|
|
110079
|
+
}
|
|
110080
|
+
};
|
|
109857
110081
|
}
|
|
109858
110082
|
async function readLarkSnapshotBundle(directory, target) {
|
|
109859
110083
|
try {
|
|
109860
110084
|
const root2 = await assertSnapshotDirectory(directory);
|
|
109861
|
-
const path3 =
|
|
110085
|
+
const path3 = join121(root2, FILE2);
|
|
109862
110086
|
const stat11 = await lstat16(path3);
|
|
109863
110087
|
if (stat11.isSymbolicLink() || !stat11.isFile())
|
|
109864
110088
|
throw larkSnapshotError("Snapshot receipt must be a regular file", "path-invalid");
|
|
@@ -109886,8 +110110,8 @@ async function reserveSnapshotDirectory(directory, workspaceRoot) {
|
|
|
109886
110110
|
ancestor = dirname47(ancestor);
|
|
109887
110111
|
}
|
|
109888
110112
|
}
|
|
109889
|
-
const parent2 =
|
|
109890
|
-
const output =
|
|
110113
|
+
const parent2 = join121(ancestor, ...missing2);
|
|
110114
|
+
const output = join121(parent2, basename9(requested));
|
|
109891
110115
|
const { findContextProjectRoot: findContextProjectRoot2 } = await Promise.resolve().then(() => (init_workspace(), exports_workspace));
|
|
109892
110116
|
const owner = findContextProjectRoot2(parent2)?.projectRoot ?? workspaceRoot;
|
|
109893
110117
|
if (owner !== undefined) {
|
|
@@ -109924,6 +110148,8 @@ var init_larkSnapshotBundle = __esm(() => {
|
|
|
109924
110148
|
policySchema = exports_external.object({
|
|
109925
110149
|
images: exports_external.enum(["bundle", "reference-only"]),
|
|
109926
110150
|
gifs: exports_external.enum(["bundle", "reference-only"]),
|
|
110151
|
+
files: exports_external.enum(["bundle", "reference-only"]).optional(),
|
|
110152
|
+
whiteboards: exports_external.enum(["bundle", "reference-only"]).optional(),
|
|
109927
110153
|
videos: exports_external.enum(["bundle", "reference-only"]),
|
|
109928
110154
|
maxBytesPerResource: exports_external.number().int().positive(),
|
|
109929
110155
|
maxTotalBytes: exports_external.number().int().positive()
|
|
@@ -109961,8 +110187,9 @@ var init_larkSnapshotBundle = __esm(() => {
|
|
|
109961
110187
|
|
|
109962
110188
|
// src/project/documentCaptureLark.ts
|
|
109963
110189
|
import { createHash as createHash38 } from "node:crypto";
|
|
109964
|
-
import { readdir as
|
|
109965
|
-
import { basename as basename10, extname as extname14, join as
|
|
110190
|
+
import { readdir as readdir29, readFile as readFile98 } from "node:fs/promises";
|
|
110191
|
+
import { basename as basename10, extname as extname14, join as join122 } from "node:path";
|
|
110192
|
+
import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
|
|
109966
110193
|
function titleFromMarkdown2(markdown, fallbackPath) {
|
|
109967
110194
|
const heading2 = markdown.split(`
|
|
109968
110195
|
`).find((line) => /^#\s+\S/u.test(line));
|
|
@@ -109989,7 +110216,7 @@ async function fileContentMatches(path3, content3) {
|
|
|
109989
110216
|
}
|
|
109990
110217
|
}
|
|
109991
110218
|
function sourceManifestPath2(entry) {
|
|
109992
|
-
return entry.snapshot?.manifest ??
|
|
110219
|
+
return entry.snapshot?.manifest ?? join122(entry.materializedAt, "manifest.json");
|
|
109993
110220
|
}
|
|
109994
110221
|
function larkRuntimeError(message, detail) {
|
|
109995
110222
|
return new ContextError(ExitCode.ExternalToolError, message, {
|
|
@@ -110121,13 +110348,57 @@ function assetManifestEntry(asset, assetRoot) {
|
|
|
110121
110348
|
...asset.bytes !== undefined ? { bytes: asset.bytes } : {}
|
|
110122
110349
|
};
|
|
110123
110350
|
}
|
|
110351
|
+
function earlierLarkResources(projectRoot, materializedAt, manifest, budgetExcluded) {
|
|
110352
|
+
const byResource = new Map;
|
|
110353
|
+
for (const asset of manifest.assets ?? []) {
|
|
110354
|
+
const source2 = asset.source;
|
|
110355
|
+
if (asset.role !== "evidence" || source2?.kind !== "image" && source2?.kind !== "file" || !source2.locator || !source2.identity || !asset.content_hash || !asset.media_type)
|
|
110356
|
+
continue;
|
|
110357
|
+
byResource.set(`${source2.kind}\x00${source2.locator}`, asset);
|
|
110358
|
+
}
|
|
110359
|
+
if (byResource.size === 0 && budgetExcluded === undefined)
|
|
110360
|
+
return;
|
|
110361
|
+
const revisionId = manifest.metadata?.source?.revisionId;
|
|
110362
|
+
const rawContentHash = manifest.assets?.find((asset) => asset.source?.kind === "lark-docx-xml")?.source?.raw_content_hash;
|
|
110363
|
+
return {
|
|
110364
|
+
...revisionId === undefined ? {} : { revisionId },
|
|
110365
|
+
...rawContentHash === undefined ? {} : { rawContentHash },
|
|
110366
|
+
...budgetExcluded === undefined ? {} : { budgetExcluded },
|
|
110367
|
+
load: async (resource, identity2) => {
|
|
110368
|
+
const asset = byResource.get(`${resource.kind}\x00${resource.locator}`);
|
|
110369
|
+
if (asset === undefined || asset.source?.identity !== identity2)
|
|
110370
|
+
return;
|
|
110371
|
+
let bytes;
|
|
110372
|
+
try {
|
|
110373
|
+
bytes = await readFile98(join122(projectRoot, materializedAt, asset.path));
|
|
110374
|
+
} catch {
|
|
110375
|
+
return;
|
|
110376
|
+
}
|
|
110377
|
+
if (computeDocumentContentHash(bytes) !== asset.content_hash)
|
|
110378
|
+
return;
|
|
110379
|
+
return {
|
|
110380
|
+
path: asset.path,
|
|
110381
|
+
bytes,
|
|
110382
|
+
mediaType: asset.media_type,
|
|
110383
|
+
representation: asset.source.representation === "preview" ? "preview" : "original"
|
|
110384
|
+
};
|
|
110385
|
+
}
|
|
110386
|
+
};
|
|
110387
|
+
}
|
|
110388
|
+
function budgetExcludedImages(report, policy) {
|
|
110389
|
+
const budget = report?.resource_budget;
|
|
110390
|
+
if (budget === undefined || report?.access === undefined || policy.maxBytesPerResource > budget.maxBytesPerResource || policy.maxTotalBytes > budget.maxTotalBytes)
|
|
110391
|
+
return;
|
|
110392
|
+
const locators = new Set(report.resources.filter((item) => item.kind === "image" && item.reason_code === "image-budget-exceeded").map((item) => item.locator));
|
|
110393
|
+
return locators.size === 0 ? undefined : { identity: report.access.identity, locators };
|
|
110394
|
+
}
|
|
110124
110395
|
async function listSnapshotAssetFiles(root2, assetRoot) {
|
|
110125
|
-
const assetsRoot =
|
|
110396
|
+
const assetsRoot = join122(root2, assetRoot);
|
|
110126
110397
|
const files = [];
|
|
110127
110398
|
const visit4 = async (dir, prefix = assetRoot) => {
|
|
110128
110399
|
let entries2;
|
|
110129
110400
|
try {
|
|
110130
|
-
entries2 = await
|
|
110401
|
+
entries2 = await readdir29(dir, { withFileTypes: true });
|
|
110131
110402
|
} catch (error) {
|
|
110132
110403
|
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
110133
110404
|
return;
|
|
@@ -110135,7 +110406,7 @@ async function listSnapshotAssetFiles(root2, assetRoot) {
|
|
|
110135
110406
|
}
|
|
110136
110407
|
for (const entry of entries2) {
|
|
110137
110408
|
const relPath = `${prefix}/${entry.name}`;
|
|
110138
|
-
const absolutePath =
|
|
110409
|
+
const absolutePath = join122(dir, entry.name);
|
|
110139
110410
|
if (entry.isDirectory()) {
|
|
110140
110411
|
await visit4(absolutePath, relPath);
|
|
110141
110412
|
continue;
|
|
@@ -110150,7 +110421,7 @@ async function listSnapshotAssetFiles(root2, assetRoot) {
|
|
|
110150
110421
|
}
|
|
110151
110422
|
async function staleSnapshotAssetPaths(input) {
|
|
110152
110423
|
const existingPaths = await listSnapshotAssetFiles(input.materializedAtAbsPath, input.assetRoot);
|
|
110153
|
-
return existingPaths.filter((path3) => !input.currentPaths.has(path3)).map((path3) =>
|
|
110424
|
+
return existingPaths.filter((path3) => !input.currentPaths.has(path3)).map((path3) => join122(input.materializedAtAbsPath, path3));
|
|
110154
110425
|
}
|
|
110155
110426
|
function normalizeLarkError(error, sourceName) {
|
|
110156
110427
|
if (error instanceof ContextError)
|
|
@@ -110214,7 +110485,7 @@ async function runCaptureLarkPhaseUnlocked(input) {
|
|
|
110214
110485
|
const target = larkTarget(entry);
|
|
110215
110486
|
const manifestPath = sourceManifestPath2(entry);
|
|
110216
110487
|
const materializedAt = entry.materializedAt;
|
|
110217
|
-
const materializedAtAbsPath =
|
|
110488
|
+
const materializedAtAbsPath = join122(input.projectRoot, materializedAt);
|
|
110218
110489
|
const { current: currentManifestFile, previous: previousManifest, recovery } = await readDocumentManifestForCapture({
|
|
110219
110490
|
projectRoot: input.projectRoot,
|
|
110220
110491
|
manifestPath,
|
|
@@ -110224,7 +110495,16 @@ async function runCaptureLarkPhaseUnlocked(input) {
|
|
|
110224
110495
|
const fingerprint = previousManifest === null || larkSnapshotIdentityDiagnostic(entry, previousManifest) !== null ? undefined : await larkSnapshotFingerprint(input.projectRoot, materializedAt, previousManifest);
|
|
110225
110496
|
const refresh = input.refreshSources?.includes(`lark:${resolved.sourceName}`) === true;
|
|
110226
110497
|
const previousRevision = (fingerprint === undefined ? undefined : await checkedLarkRevision(input.projectRoot, resolved.sourceName, fingerprint)) ?? previousManifest?.metadata?.source?.revisionId;
|
|
110227
|
-
const unchangedRevisionId = !refresh && !input.prefetched && !recovery &&
|
|
110498
|
+
const unchangedRevisionId = !refresh && !input.prefetched && !recovery && isDeepStrictEqual3(normalizedSnapshotResourcePolicy({ ...DEFAULT_RESOURCE_POLICY, ...input.phase.resources }), normalizedSnapshotResourcePolicy(DEFAULT_RESOURCE_POLICY)) && previousManifest?.normalizer_version === LARK_DOCUMENT_NORMALIZER_VERSION && fingerprint !== undefined ? previousRevision : undefined;
|
|
110499
|
+
let reuseResources;
|
|
110500
|
+
if (previousManifest !== null && !recovery && !input.prefetched && larkSnapshotIdentityDiagnostic(entry, previousManifest) === null) {
|
|
110501
|
+
try {
|
|
110502
|
+
const report = readDocumentSnapshotCaptureReport({ projectRoot: input.projectRoot, materializedAt, manifest: previousManifest });
|
|
110503
|
+
if (documentSnapshotFidelityState(previousManifest, report).resourceMaterialization?.status === "error") {
|
|
110504
|
+
reuseResources = earlierLarkResources(input.projectRoot, materializedAt, previousManifest, budgetExcludedImages(report, { ...DEFAULT_RESOURCE_POLICY, ...input.phase.resources }));
|
|
110505
|
+
}
|
|
110506
|
+
} catch {}
|
|
110507
|
+
}
|
|
110228
110508
|
await beginFormatOnlyUpdate(input.projectRoot);
|
|
110229
110509
|
let unchangedAccess;
|
|
110230
110510
|
if (typeof unchangedRevisionId === "string" && previousManifest !== null) {
|
|
@@ -110246,6 +110526,7 @@ async function runCaptureLarkPhaseUnlocked(input) {
|
|
|
110246
110526
|
url: target.value,
|
|
110247
110527
|
resourcePolicy: input.phase.resources,
|
|
110248
110528
|
requireCompleteBody: true,
|
|
110529
|
+
...reuseResources === undefined ? {} : { reuseResources },
|
|
110249
110530
|
...typeof unchangedRevisionId === "string" ? { unchangedRevisionId } : {},
|
|
110250
110531
|
...unchangedAccess === undefined ? {} : { unchangedAccess },
|
|
110251
110532
|
accessEvents,
|
|
@@ -110312,7 +110593,7 @@ async function runCaptureLarkPhaseUnlocked(input) {
|
|
|
110312
110593
|
manifest: previousManifest
|
|
110313
110594
|
}));
|
|
110314
110595
|
let lost = fetched.resourceMaterialization.items.filter((item) => previous3.resourceMaterialization?.items.some((old) => old.kind === item.kind && old.locator === item.locator && old.status === "materialized" && (item.status !== "materialized" || item.reason_code === "document.resource.preview" && old.reason_code !== "document.resource.preview")));
|
|
110315
|
-
degraded = lost.filter((item) => item.status === "materialized" || isNonBlockingDocumentResourceFailureReasonCode(item.reason_code));
|
|
110596
|
+
degraded = lost.filter((item) => item.status === "materialized" || isNonBlockingDocumentResourceFailureReasonCode(item.reason_code) || LARK_POLICY_EXCLUSION_REASON_CODES.has(item.reason_code ?? ""));
|
|
110316
110597
|
lost = lost.filter((item) => !degraded.includes(item));
|
|
110317
110598
|
if (lost.length)
|
|
110318
110599
|
throw new ContextError(ExitCode.WorkspaceStateError, "Previously captured resources were degraded; the existing snapshot was preserved. Check resource policy and access before retrying the explicit refresh.", {
|
|
@@ -110361,7 +110642,7 @@ async function runCaptureLarkPhaseUnlocked(input) {
|
|
|
110361
110642
|
title: title2,
|
|
110362
110643
|
locator
|
|
110363
110644
|
}];
|
|
110364
|
-
const manifestAbsPath =
|
|
110645
|
+
const manifestAbsPath = join122(input.projectRoot, manifestPath);
|
|
110365
110646
|
const manifest = createDocumentSnapshotManifest({
|
|
110366
110647
|
sourceType: "lark",
|
|
110367
110648
|
sourceName: resolved.sourceName,
|
|
@@ -110391,13 +110672,13 @@ async function runCaptureLarkPhaseUnlocked(input) {
|
|
|
110391
110672
|
const cacheDiagnostics = [];
|
|
110392
110673
|
try {
|
|
110393
110674
|
const requestedWrites = [{
|
|
110394
|
-
path:
|
|
110675
|
+
path: join122(materializedAtAbsPath, documentPath),
|
|
110395
110676
|
bytes: normalized
|
|
110396
110677
|
}];
|
|
110397
110678
|
for (const asset of assets) {
|
|
110398
110679
|
if (asset.bytes !== undefined) {
|
|
110399
110680
|
requestedWrites.push({
|
|
110400
|
-
path:
|
|
110681
|
+
path: join122(materializedAtAbsPath, asset.entry.path),
|
|
110401
110682
|
bytes: asset.bytes
|
|
110402
110683
|
});
|
|
110403
110684
|
}
|
|
@@ -110431,7 +110712,7 @@ async function runCaptureLarkPhaseUnlocked(input) {
|
|
|
110431
110712
|
if (relativePath in capturedFiles)
|
|
110432
110713
|
continue;
|
|
110433
110714
|
try {
|
|
110434
|
-
capturedFiles[relativePath] = `sha256:${createHash38("sha256").update(await readFile98(
|
|
110715
|
+
capturedFiles[relativePath] = `sha256:${createHash38("sha256").update(await readFile98(join122(input.projectRoot, relativePath))).digest("hex")}`;
|
|
110435
110716
|
} catch (error) {
|
|
110436
110717
|
if (error.code === "ENOENT")
|
|
110437
110718
|
capturedFiles[relativePath] = null;
|
|
@@ -110440,7 +110721,7 @@ async function runCaptureLarkPhaseUnlocked(input) {
|
|
|
110440
110721
|
}
|
|
110441
110722
|
}
|
|
110442
110723
|
await applyAtomicFileBatch({
|
|
110443
|
-
transactionRoot:
|
|
110724
|
+
transactionRoot: join122(input.projectRoot, ".tmp", "context-runtime", "capture-transactions"),
|
|
110444
110725
|
writes,
|
|
110445
110726
|
removals
|
|
110446
110727
|
});
|
|
@@ -110548,6 +110829,7 @@ var init_documentCaptureLark = __esm(() => {
|
|
|
110548
110829
|
init_writeLock();
|
|
110549
110830
|
init_sensitiveSourceLiteral();
|
|
110550
110831
|
init_larkSnapshotBundle();
|
|
110832
|
+
init_larkImagePolicy();
|
|
110551
110833
|
init_larkCaptureFreshness();
|
|
110552
110834
|
init_documentSnapshotFidelity();
|
|
110553
110835
|
init_formatOnlyUpdate();
|
|
@@ -110625,8 +110907,8 @@ __export(exports_writeLockRecovery, {
|
|
|
110625
110907
|
recoverWriterLock: () => recoverWriterLock,
|
|
110626
110908
|
inspectWriterLock: () => inspectWriterLock
|
|
110627
110909
|
});
|
|
110628
|
-
import { lstat as lstat17, mkdir as mkdir41, readFile as readFile104, readdir as
|
|
110629
|
-
import { join as
|
|
110910
|
+
import { lstat as lstat17, mkdir as mkdir41, readFile as readFile104, readdir as readdir30, rename as rename11, rmdir as rmdir2 } from "node:fs/promises";
|
|
110911
|
+
import { join as join127 } from "node:path";
|
|
110630
110912
|
import { createHash as createHash40, randomUUID as randomUUID8 } from "node:crypto";
|
|
110631
110913
|
async function inspectWriterLock(root2) {
|
|
110632
110914
|
const path3 = await safeProjectTarget(root2, lockRelative);
|
|
@@ -110677,19 +110959,19 @@ async function recoverWriterLock(input) {
|
|
|
110677
110959
|
};
|
|
110678
110960
|
if (input.plan_digest !== revision)
|
|
110679
110961
|
throw new Error("Writer lock or transactions changed; preview recovery again.");
|
|
110680
|
-
const path3 =
|
|
110681
|
-
const guard =
|
|
110962
|
+
const path3 = join127(input.projectRoot, lockRelative);
|
|
110963
|
+
const guard = join127(path3, ".recovery");
|
|
110682
110964
|
await mkdir41(guard);
|
|
110683
110965
|
let archived = false;
|
|
110684
110966
|
try {
|
|
110685
110967
|
const current3 = await inspectWriterLock(input.projectRoot);
|
|
110686
110968
|
if (current3?.digest !== before.digest || current3.process_state !== "not-running")
|
|
110687
110969
|
throw new Error("Writer lock changed or owner resumed; keep the lock.");
|
|
110688
|
-
const names = await
|
|
110970
|
+
const names = await readdir30(path3);
|
|
110689
110971
|
if (names.some((name3) => name3 !== "owner.json" && name3 !== ".recovery"))
|
|
110690
110972
|
throw new Error("Unexpected lock contents; preserve for diagnosis.");
|
|
110691
110973
|
const archive = `.tmp/context-runtime/locks/recovered-write-${randomUUID8()}.lock`;
|
|
110692
|
-
await rename11(path3,
|
|
110974
|
+
await rename11(path3, join127(input.projectRoot, archive));
|
|
110693
110975
|
archived = true;
|
|
110694
110976
|
const receipts = await withProjectWriteLock(input.projectRoot, "recover-writer-transactions", async () => {
|
|
110695
110977
|
if (JSON.stringify(await recoveryJournals(input.projectRoot)) !== JSON.stringify(journals)) {
|
|
@@ -110722,8 +111004,8 @@ __export(exports_taskRecovery, {
|
|
|
110722
111004
|
RECOVERY_COMMAND: () => RECOVERY_COMMAND
|
|
110723
111005
|
});
|
|
110724
111006
|
import { existsSync as existsSync32 } from "node:fs";
|
|
110725
|
-
import { basename as basename11, dirname as dirname50, join as
|
|
110726
|
-
import { lstat as lstat18, readdir as
|
|
111007
|
+
import { basename as basename11, dirname as dirname50, join as join128 } from "node:path";
|
|
111008
|
+
import { lstat as lstat18, readdir as readdir31, readFile as readFile105 } from "node:fs/promises";
|
|
110727
111009
|
async function recoveryText(root2, path3) {
|
|
110728
111010
|
const target = await safeProjectTarget(root2, path3);
|
|
110729
111011
|
try {
|
|
@@ -110740,7 +111022,7 @@ async function recoveryJournals(root2) {
|
|
|
110740
111022
|
await safeProjectTarget(root2, path3);
|
|
110741
111023
|
let stat11;
|
|
110742
111024
|
try {
|
|
110743
|
-
stat11 = await lstat18(
|
|
111025
|
+
stat11 = await lstat18(join128(root2, path3));
|
|
110744
111026
|
} catch (error) {
|
|
110745
111027
|
if (error.code === "ENOENT")
|
|
110746
111028
|
return;
|
|
@@ -110751,7 +111033,7 @@ async function recoveryJournals(root2) {
|
|
|
110751
111033
|
if (stat11.isDirectory()) {
|
|
110752
111034
|
if (depth > 3)
|
|
110753
111035
|
throw new TypeError("Unexpected transaction directory depth; preserve it for diagnosis.");
|
|
110754
|
-
for (const name3 of (await
|
|
111036
|
+
for (const name3 of (await readdir31(join128(root2, path3))).sort())
|
|
110755
111037
|
await visit4(`${path3}/${name3}`, depth + 1);
|
|
110756
111038
|
} else if (stat11.isFile())
|
|
110757
111039
|
entries2.push({ path: path3, digest: indexerProtocolDigest(await recoveryText(root2, path3)) });
|
|
@@ -110763,8 +111045,8 @@ function recoveryResources() {
|
|
|
110763
111045
|
try {
|
|
110764
111046
|
const root2 = dirname50(contextWorkflowProviderPath());
|
|
110765
111047
|
const resources = {
|
|
110766
|
-
skill:
|
|
110767
|
-
issue_template:
|
|
111048
|
+
skill: join128(root2, "skills/recover-workspace/SKILL.md"),
|
|
111049
|
+
issue_template: join128(root2, "resources/templates/recovery-issue.md")
|
|
110768
111050
|
};
|
|
110769
111051
|
if (!Object.values(resources).every((path3) => existsSync32(path3)))
|
|
110770
111052
|
throw new Error("Recovery resources are absent from this Provider.");
|
|
@@ -110880,7 +111162,7 @@ __export(exports_taskLocalSourceAdjustment, {
|
|
|
110880
111162
|
adjustLocalRevisionSources: () => adjustLocalRevisionSources
|
|
110881
111163
|
});
|
|
110882
111164
|
import { readFile as readFile106 } from "node:fs/promises";
|
|
110883
|
-
import { join as
|
|
111165
|
+
import { join as join129 } from "node:path";
|
|
110884
111166
|
async function adjustLocalRevisionSources(root2, input) {
|
|
110885
111167
|
const { readMaintenance: readMaintenance2 } = await Promise.resolve().then(() => (init_maintenanceStorage(), exports_maintenanceStorage));
|
|
110886
111168
|
if ((await readMaintenance2(root2)).active && await readProductionStage(root2))
|
|
@@ -110926,7 +111208,7 @@ async function adjustLocalRevisionSources(root2, input) {
|
|
|
110926
111208
|
if (input.refresh && (!current3.refresh_sources || indexerProtocolDigest([...current3.refresh_sources].sort()) !== indexerProtocolDigest([...selected].sort()))) {
|
|
110927
111209
|
throw new TypeError("No matching acquisition adjustment exists. Run task adjust without refresh first.");
|
|
110928
111210
|
}
|
|
110929
|
-
const raw = await readFile106(
|
|
111211
|
+
const raw = await readFile106(join129(root2, await revisionStoragePath(root2)), "utf8");
|
|
110930
111212
|
let next2;
|
|
110931
111213
|
const discardIds = new Set;
|
|
110932
111214
|
if (!refresh) {
|
|
@@ -111041,7 +111323,7 @@ ${input.instruction}` : revision.instruction
|
|
|
111041
111323
|
content: content3
|
|
111042
111324
|
}];
|
|
111043
111325
|
if (discardIds.size > 0) {
|
|
111044
|
-
const ledger = await readFile106(
|
|
111326
|
+
const ledger = await readFile106(join129(root2, CANDIDATE_LEDGER_FILE), "utf8").catch((error) => {
|
|
111045
111327
|
if (error.code === "ENOENT")
|
|
111046
111328
|
return;
|
|
111047
111329
|
throw error;
|
|
@@ -111389,7 +111671,7 @@ __export(exports_approvedRevisionSubmission, {
|
|
|
111389
111671
|
prepareApprovedRevisionSubmission: () => prepareApprovedRevisionSubmission,
|
|
111390
111672
|
completeApprovedRevisionSubmission: () => completeApprovedRevisionSubmission
|
|
111391
111673
|
});
|
|
111392
|
-
import { join as
|
|
111674
|
+
import { join as join131 } from "node:path";
|
|
111393
111675
|
function paused(message, managed, authorities = []) {
|
|
111394
111676
|
return new ContextError(ExitCode.WorkspaceStateError, message, {
|
|
111395
111677
|
category: ErrorCategory.WorkspaceStateInvalid,
|
|
@@ -111444,9 +111726,9 @@ async function prepareApprovedRevisionSubmission(input) {
|
|
|
111444
111726
|
const { route, requests, contexts, issued } = await issueRevisionBatch(input);
|
|
111445
111727
|
const stage = stageId(issued);
|
|
111446
111728
|
const directory = productionAgentDirectory(stage);
|
|
111447
|
-
await atomicWriteFile(await safeProjectTarget(input.projectRoot,
|
|
111729
|
+
await atomicWriteFile(await safeProjectTarget(input.projectRoot, join131(directory, "issued.json")), JSON.stringify(issued));
|
|
111448
111730
|
for (const [index3, request] of requests.entries()) {
|
|
111449
|
-
await atomicWriteFile(await safeProjectTarget(input.projectRoot,
|
|
111731
|
+
await atomicWriteFile(await safeProjectTarget(input.projectRoot, join131(directory, `${issued.tasks[index3].task}.input.json`)), JSON.stringify({
|
|
111450
111732
|
stage: "approved-revision",
|
|
111451
111733
|
revision: request.revision,
|
|
111452
111734
|
instruction: request.instruction,
|
|
@@ -111461,7 +111743,7 @@ async function prepareApprovedRevisionSubmission(input) {
|
|
|
111461
111743
|
tasks: issued.tasks.map((task, index3) => ({
|
|
111462
111744
|
...task,
|
|
111463
111745
|
path: requests[index3].target.path,
|
|
111464
|
-
task_input:
|
|
111746
|
+
task_input: join131(directory, `${task.task}.input.json`)
|
|
111465
111747
|
})),
|
|
111466
111748
|
submission: { stage, tasks: issued.tasks.map((task) => ({ task: task.task, input: task.input, edits: `${task.task}.edits.json` })) },
|
|
111467
111749
|
next_action: {
|
|
@@ -111633,7 +111915,10 @@ async function previewApprovedRevisionSubmission(input) {
|
|
|
111633
111915
|
const semantic = parseIndexerCurrentActionSubmission(value);
|
|
111634
111916
|
if (semantic.stage !== "approved-revision")
|
|
111635
111917
|
throw new TypeError(`Task ${task.task} is not an approved revision.`);
|
|
111636
|
-
const request =
|
|
111918
|
+
const request = {
|
|
111919
|
+
...JSON.parse((await readProductionFile({ projectRoot: input.projectRoot, stage: manifest.stage, path: `${task.task}.input.json` })).text),
|
|
111920
|
+
...current3.requests[index3]?.processed_scopes ? { processed_scopes: current3.requests[index3].processed_scopes } : {}
|
|
111921
|
+
};
|
|
111637
111922
|
const content3 = "markdown" in semantic ? { markdown: semantic.markdown, ...semantic.sections === undefined ? {} : { sections: semantic.sections } } : { sections: semantic.sections };
|
|
111638
111923
|
const { markdown, references, reference_warnings } = await composeRevisionCandidate2(input.projectRoot, request, content3, { remember: false });
|
|
111639
111924
|
pages.push({
|
|
@@ -111830,7 +112115,7 @@ __export(exports_managedDocumentRename, {
|
|
|
111830
112115
|
renameManagedDocument: () => renameManagedDocument
|
|
111831
112116
|
});
|
|
111832
112117
|
import { readFile as readFile117 } from "node:fs/promises";
|
|
111833
|
-
import { join as
|
|
112118
|
+
import { join as join143, posix as posix15 } from "node:path";
|
|
111834
112119
|
async function optionalText3(path3) {
|
|
111835
112120
|
try {
|
|
111836
112121
|
return await readFile117(path3, "utf8");
|
|
@@ -111917,7 +112202,7 @@ async function renameManagedDocument(input) {
|
|
|
111917
112202
|
if (path3.split("/").includes("..") || path3.startsWith("/"))
|
|
111918
112203
|
throw new TypeError("Source references contain an unsafe knowledge path; repair it before renaming.");
|
|
111919
112204
|
await safeProjectTarget(input.projectRoot, path3);
|
|
111920
|
-
const before = await optionalText3(
|
|
112205
|
+
const before = await optionalText3(join143(input.projectRoot, path3));
|
|
111921
112206
|
if (before === undefined)
|
|
111922
112207
|
continue;
|
|
111923
112208
|
let after;
|
|
@@ -112075,7 +112360,7 @@ var init_originalRevisionsCommand = __esm(() => {
|
|
|
112075
112360
|
|
|
112076
112361
|
// src/cli.ts
|
|
112077
112362
|
import { existsSync as existsSync41, realpathSync as realpathSync3 } from "node:fs";
|
|
112078
|
-
import { dirname as dirname57, join as
|
|
112363
|
+
import { dirname as dirname57, join as join149 } from "node:path";
|
|
112079
112364
|
import { fileURLToPath as fileURLToPath12, pathToFileURL as pathToFileURL3 } from "node:url";
|
|
112080
112365
|
|
|
112081
112366
|
// ../../node_modules/.bun/commander@11.1.0/node_modules/commander/esm.mjs
|
|
@@ -116856,14 +117141,14 @@ function compactJsonResult(result, verbose) {
|
|
|
116856
117141
|
// src/project/runLog.ts
|
|
116857
117142
|
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
116858
117143
|
import { mkdir as mkdir40, writeFile as writeFile31 } from "node:fs/promises";
|
|
116859
|
-
import { dirname as dirname48, join as
|
|
117144
|
+
import { dirname as dirname48, join as join123 } from "node:path";
|
|
116860
117145
|
var createPhaseRunId = () => {
|
|
116861
117146
|
const timestamp = new Date().toISOString().replace(/[-:.TZ]/gu, "");
|
|
116862
117147
|
return `run_${timestamp}_${randomUUID6().slice(0, 8)}`;
|
|
116863
117148
|
};
|
|
116864
117149
|
async function writePhaseRunLog(input) {
|
|
116865
|
-
const relPath =
|
|
116866
|
-
const absPath =
|
|
117150
|
+
const relPath = join123(".tmp", "context-runtime", "runs", `${input.runId}.json`);
|
|
117151
|
+
const absPath = join123(input.projectRoot, relPath);
|
|
116867
117152
|
await mkdir40(dirname48(absPath), { recursive: true });
|
|
116868
117153
|
await writeFile31(absPath, `${JSON.stringify({
|
|
116869
117154
|
run_id: input.runId,
|
|
@@ -118112,7 +118397,7 @@ init_durableSingleFileTransaction();
|
|
|
118112
118397
|
init_reviewShared();
|
|
118113
118398
|
import { existsSync as existsSync30 } from "node:fs";
|
|
118114
118399
|
import { readFile as readFile99 } from "node:fs/promises";
|
|
118115
|
-
import { join as
|
|
118400
|
+
import { join as join124 } from "node:path";
|
|
118116
118401
|
function existingTimestamp(markdown) {
|
|
118117
118402
|
if (markdown === undefined)
|
|
118118
118403
|
return;
|
|
@@ -118139,7 +118424,7 @@ async function prepareApprovedPage(input) {
|
|
|
118139
118424
|
next: "Refresh the current production or article revision, then reopen Review before approval."
|
|
118140
118425
|
});
|
|
118141
118426
|
}
|
|
118142
|
-
const relPath =
|
|
118427
|
+
const relPath = join124("knowledge", input.record.path);
|
|
118143
118428
|
const existingView = findApprovedPageForArticleId(input.record.indexer_candidate.artifact_ref, input.approvedPageIndex);
|
|
118144
118429
|
const previousPath = input.record.approved_revision?.previous_path;
|
|
118145
118430
|
if (previousPath !== undefined && (!isSafeKnowledgeTargetPath(previousPath.split("/")[0], previousPath) || previousPath.includes("\\")))
|
|
@@ -118154,13 +118439,13 @@ async function prepareApprovedPage(input) {
|
|
|
118154
118439
|
next: "Resolve the approved page path migration explicitly before approving this candidate."
|
|
118155
118440
|
});
|
|
118156
118441
|
}
|
|
118157
|
-
const absPath =
|
|
118442
|
+
const absPath = join124(input.projectRoot, relPath);
|
|
118158
118443
|
const existing = existsSync30(absPath) ? await readFile99(absPath, "utf8") : undefined;
|
|
118159
118444
|
let previous3;
|
|
118160
118445
|
if (previousPath !== undefined) {
|
|
118161
118446
|
if (existing !== undefined || existingView?.relPath !== `knowledge/${previousPath}`)
|
|
118162
118447
|
throw new TypeError("Page move destination or original identity changed; refresh its revision.");
|
|
118163
|
-
previous3 = { path: `knowledge/${previousPath}`, content: await readFile99(
|
|
118448
|
+
previous3 = { path: `knowledge/${previousPath}`, content: await readFile99(join124(input.projectRoot, "knowledge", previousPath), "utf8") };
|
|
118164
118449
|
}
|
|
118165
118450
|
if (input.record.approved_revision !== undefined) {
|
|
118166
118451
|
const base = previous3?.content ?? existing;
|
|
@@ -118207,7 +118492,7 @@ async function prepareApprovedPage(input) {
|
|
|
118207
118492
|
}
|
|
118208
118493
|
async function readProjectFileMaybe(projectRoot, relPath) {
|
|
118209
118494
|
try {
|
|
118210
|
-
return await readFile99(
|
|
118495
|
+
return await readFile99(join124(projectRoot, relPath), "utf8");
|
|
118211
118496
|
} catch (error) {
|
|
118212
118497
|
if (error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT") {
|
|
118213
118498
|
return;
|
|
@@ -118428,7 +118713,7 @@ async function applyReviewDecisions(input) {
|
|
|
118428
118713
|
});
|
|
118429
118714
|
}
|
|
118430
118715
|
seenApprovedIds.set(approvedRef, row.candidate_id);
|
|
118431
|
-
const approvedPath =
|
|
118716
|
+
const approvedPath = join124("knowledge", row.path);
|
|
118432
118717
|
const previousPathCandidate = seenApprovedPaths.get(knowledgeTargetPathKey(approvedPath));
|
|
118433
118718
|
if (previousPathCandidate !== undefined) {
|
|
118434
118719
|
throw new ContextError(ExitCode.UserError, `multiple approved review decisions target the same knowledge path: ${approvedPath}`, {
|
|
@@ -118478,7 +118763,7 @@ async function applyReviewDecisions(input) {
|
|
|
118478
118763
|
for (const path3 of approvedPageIndex.byRelPath.keys()) {
|
|
118479
118764
|
if (pagesToWrite.some((page) => page.relPath === path3 || page.previous?.path === path3))
|
|
118480
118765
|
continue;
|
|
118481
|
-
const before = await readFile99(
|
|
118766
|
+
const before = await readFile99(join124(input.projectRoot, path3), "utf8");
|
|
118482
118767
|
const local = path3.replace(/^knowledge\//u, "");
|
|
118483
118768
|
const after = moveKnowledgeLinkTargets2(before, local, local, moved);
|
|
118484
118769
|
navigationTargets.push(reviewFileTarget({ path: path3, baseContent: before, targetContent: after }));
|
|
@@ -118569,12 +118854,12 @@ init_candidateLedger();
|
|
|
118569
118854
|
|
|
118570
118855
|
// src/project/localHtmlReport.ts
|
|
118571
118856
|
import { execFile as execFile18 } from "node:child_process";
|
|
118572
|
-
import { isAbsolute as isAbsolute20, join as
|
|
118857
|
+
import { isAbsolute as isAbsolute20, join as join125 } from "node:path";
|
|
118573
118858
|
import { pathToFileURL as pathToFileURL2 } from "node:url";
|
|
118574
118859
|
import { promisify as promisify15 } from "node:util";
|
|
118575
118860
|
var execFileAsync4 = promisify15(execFile18);
|
|
118576
118861
|
function htmlReportReference(input) {
|
|
118577
|
-
const absolutePath = isAbsolute20(input.path) ? input.path :
|
|
118862
|
+
const absolutePath = isAbsolute20(input.path) ? input.path : join125(input.projectRoot, input.path);
|
|
118578
118863
|
return {
|
|
118579
118864
|
format: "html",
|
|
118580
118865
|
path: input.path,
|
|
@@ -119763,7 +120048,7 @@ init_maintenanceStorage();
|
|
|
119763
120048
|
init_productionFeedback();
|
|
119764
120049
|
import { randomUUID as randomUUID7 } from "node:crypto";
|
|
119765
120050
|
import { readFile as readFile103 } from "node:fs/promises";
|
|
119766
|
-
import { join as
|
|
120051
|
+
import { join as join126 } from "node:path";
|
|
119767
120052
|
async function beginProductionRevision(input) {
|
|
119768
120053
|
return withProductionFeedback({ operation: "revision" }, () => withProjectWriteLock(input.projectRoot, "production-revision", async () => {
|
|
119769
120054
|
await recoverDurableMultiFileTransactions(input.projectRoot);
|
|
@@ -119802,7 +120087,7 @@ async function beginProductionRevision(input) {
|
|
|
119802
120087
|
const formal = approved.byPath.get(path3);
|
|
119803
120088
|
if (!prior && !formal)
|
|
119804
120089
|
throw invalid3("Write the current task first; there is no article draft to revise yet.");
|
|
119805
|
-
const markdown = prior?.body ?? await readFile103(await safeProjectTarget(input.projectRoot,
|
|
120090
|
+
const markdown = prior?.body ?? await readFile103(await safeProjectTarget(input.projectRoot, join126("knowledge", path3)), "utf8");
|
|
119806
120091
|
const sections = prior?.indexer_candidate.sections.map((section) => ({ id: section.section_key, references: section.references })) ?? formal?.sections;
|
|
119807
120092
|
const sources = [];
|
|
119808
120093
|
for (const source2 of owner.sources) {
|
|
@@ -120199,14 +120484,22 @@ function registerDocumentRevisionCommand(program2) {
|
|
|
120199
120484
|
process.stdout.write(`${JSON.stringify(result, null, 2)}
|
|
120200
120485
|
`);
|
|
120201
120486
|
});
|
|
120202
|
-
program2.command("update").description("Inspect acquired source changes against approved knowledge in confirmed requirement scopes").option("--input <file>", "YAML/JSON scopes and optional change summary; - for stdin").option("--pending", "process registered repository commits that moved past their processed versions").option("--format <format>", "output format: json", "json").action(async (options) => {
|
|
120487
|
+
program2.command("update").description("Inspect acquired source changes against approved knowledge in confirmed requirement scopes").option("--input <file>", "YAML/JSON scopes and optional change summary; - for stdin").option("--pending", "process registered repository commits that moved past their processed versions").option("--schema", "show the update input schema").option("--format <format>", "output format: json", "json").action(async (options) => {
|
|
120488
|
+
if (options.schema) {
|
|
120489
|
+
const { knowledgeUpdateInputSchema: knowledgeUpdateInputSchema2 } = await Promise.resolve().then(() => (init_knowledgeUpdate(), exports_knowledgeUpdate));
|
|
120490
|
+
const { zodToJsonSchema: zodToJsonSchema3 } = await Promise.resolve().then(() => (init_esm(), exports_esm));
|
|
120491
|
+
const { writeSchemaOutput: writeSchemaOutput2, schemaOutputFormat: schemaOutputFormat2 } = await Promise.resolve().then(() => (init_schemaOutput(), exports_schemaOutput));
|
|
120492
|
+
writeSchemaOutput2(zodToJsonSchema3(knowledgeUpdateInputSchema2, { effectStrategy: "input" }), schemaOutputFormat2(options.format));
|
|
120493
|
+
return;
|
|
120494
|
+
}
|
|
120203
120495
|
if (options.format !== "json")
|
|
120204
120496
|
throw new ContextError(ExitCode.UserError, "--format must be json", {
|
|
120205
120497
|
category: ErrorCategory.UserInputInvalid
|
|
120206
120498
|
});
|
|
120207
120499
|
if (!options.pending === !options.input)
|
|
120208
|
-
throw new ContextError(ExitCode.UserError, "Pass exactly one of --input or --pending", {
|
|
120209
|
-
category: ErrorCategory.UserInputInvalid
|
|
120500
|
+
throw new ContextError(ExitCode.UserError, "Pass exactly one of --input or --pending, or --schema", {
|
|
120501
|
+
category: ErrorCategory.UserInputInvalid,
|
|
120502
|
+
next_action: { command: "context update --schema --format json" }
|
|
120210
120503
|
});
|
|
120211
120504
|
if (options.pending) {
|
|
120212
120505
|
process.stdout.write(`${JSON.stringify(await beginKnowledgeUpdate(requireProjectRoot2(), undefined, { pending: true }), null, 2)}
|
|
@@ -120340,7 +120633,7 @@ function registerVersionCommands(program2) {
|
|
|
120340
120633
|
|
|
120341
120634
|
// src/commands/translateCommands.ts
|
|
120342
120635
|
init_workspace();
|
|
120343
|
-
import { isAbsolute as isAbsolute22, join as
|
|
120636
|
+
import { isAbsolute as isAbsolute22, join as join130 } from "node:path";
|
|
120344
120637
|
init_status();
|
|
120345
120638
|
init_workflowCommandOptions();
|
|
120346
120639
|
init_workflowExecutionContext();
|
|
@@ -120434,7 +120727,7 @@ function registerTranslateCommands(program2) {
|
|
|
120434
120727
|
readFailureNext: "Check the input path",
|
|
120435
120728
|
parseFailureNext: "Use valid YAML or JSON"
|
|
120436
120729
|
}));
|
|
120437
|
-
const saved = await submitSiteTranslation(root2, await projectPackages(root2), value, (file) => isAbsolute22(file) ? file :
|
|
120730
|
+
const saved = await submitSiteTranslation(root2, await projectPackages(root2), value, (file) => isAbsolute22(file) ? file : join130(root2, file));
|
|
120438
120731
|
write(await withWorkflow(root2, { outcome: "submitted", ...saved }));
|
|
120439
120732
|
});
|
|
120440
120733
|
command3.command("skip").description("Publish the current pending translations in the primary language").requiredOption("--digest <digest>", "expected_digest from context translate prepare").option("--format <format>", "json", "json").action(async (options) => {
|
|
@@ -120532,7 +120825,7 @@ init_workflowRouteOutput();
|
|
|
120532
120825
|
var import_yaml57 = __toESM(require_dist(), 1);
|
|
120533
120826
|
import { Buffer as Buffer5 } from "node:buffer";
|
|
120534
120827
|
import { createHash as createHash41 } from "node:crypto";
|
|
120535
|
-
import { join as
|
|
120828
|
+
import { join as join132 } from "node:path";
|
|
120536
120829
|
var INLINE_LIMIT = 16 * 1024;
|
|
120537
120830
|
function record4(value) {
|
|
120538
120831
|
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
|
|
@@ -120558,8 +120851,8 @@ async function prepareActionCompletionOutput(input) {
|
|
|
120558
120851
|
if (production && Buffer5.byteLength(full) <= INLINE_LIMIT)
|
|
120559
120852
|
return input.result;
|
|
120560
120853
|
const digest8 = createHash41("sha256").update(full).digest("hex");
|
|
120561
|
-
const root2 =
|
|
120562
|
-
const resultFile =
|
|
120854
|
+
const root2 = join132(input.projectRoot, ".tmp/context-runtime/action-results");
|
|
120855
|
+
const resultFile = join132(root2, `${digest8}.json`);
|
|
120563
120856
|
await atomicWriteFile(resultFile, full);
|
|
120564
120857
|
if (production)
|
|
120565
120858
|
return {
|
|
@@ -120841,9 +121134,9 @@ function registerProjectActionCommands(program2) {
|
|
|
120841
121134
|
// src/commands/cleanClaudePluginCache.ts
|
|
120842
121135
|
init_cliFeedback();
|
|
120843
121136
|
import { existsSync as existsSync33 } from "node:fs";
|
|
120844
|
-
import { readdir as
|
|
121137
|
+
import { readdir as readdir32, rm as rm31 } from "node:fs/promises";
|
|
120845
121138
|
import { homedir } from "node:os";
|
|
120846
|
-
import { join as
|
|
121139
|
+
import { join as join133 } from "node:path";
|
|
120847
121140
|
var ORPHAN_MARKER = ".orphaned_at";
|
|
120848
121141
|
var CLAUDE_PLUGIN_CACHE_ROOT_ENV = "C4A_CLAUDE_PLUGIN_CACHE_ROOT";
|
|
120849
121142
|
var CLAUDE_PLUGIN_CACHE_HOME_ENV = "C4A_CLAUDE_PLUGIN_CACHE_HOME";
|
|
@@ -120856,40 +121149,40 @@ async function cleanClaudePluginCache(opts = {}) {
|
|
|
120856
121149
|
lines.push("· claude plugin cache: missing — nothing to clean");
|
|
120857
121150
|
return { lines, removed, scanned };
|
|
120858
121151
|
}
|
|
120859
|
-
const marketplaces = await
|
|
121152
|
+
const marketplaces = await readdir32(cacheRoot, { withFileTypes: true });
|
|
120860
121153
|
for (const mp of marketplaces) {
|
|
120861
121154
|
if (!mp.isDirectory())
|
|
120862
121155
|
continue;
|
|
120863
|
-
const mpDir =
|
|
120864
|
-
const plugins = await
|
|
121156
|
+
const mpDir = join133(cacheRoot, mp.name);
|
|
121157
|
+
const plugins = await readdir32(mpDir, { withFileTypes: true });
|
|
120865
121158
|
for (const pl of plugins) {
|
|
120866
121159
|
if (!pl.isDirectory())
|
|
120867
121160
|
continue;
|
|
120868
|
-
const plDir =
|
|
120869
|
-
const versions = await
|
|
121161
|
+
const plDir = join133(mpDir, pl.name);
|
|
121162
|
+
const versions = await readdir32(plDir, { withFileTypes: true });
|
|
120870
121163
|
for (const ver of versions) {
|
|
120871
121164
|
if (!ver.isDirectory())
|
|
120872
121165
|
continue;
|
|
120873
121166
|
scanned += 1;
|
|
120874
|
-
const verDir =
|
|
120875
|
-
const markerPath =
|
|
121167
|
+
const verDir = join133(plDir, ver.name);
|
|
121168
|
+
const markerPath = join133(verDir, ORPHAN_MARKER);
|
|
120876
121169
|
if (!existsSync33(markerPath))
|
|
120877
121170
|
continue;
|
|
120878
121171
|
const label2 = `${mp.name}/${pl.name}/${ver.name}`;
|
|
120879
121172
|
if (opts.dryRun) {
|
|
120880
121173
|
lines.push(` - would remove: ${label2}`);
|
|
120881
121174
|
} else {
|
|
120882
|
-
await
|
|
121175
|
+
await rm31(verDir, { recursive: true, force: true });
|
|
120883
121176
|
removed += 1;
|
|
120884
121177
|
lines.push(` ✓ removed: ${label2}`);
|
|
120885
121178
|
}
|
|
120886
121179
|
}
|
|
120887
121180
|
if (!opts.dryRun && await isEmptyDir(plDir)) {
|
|
120888
|
-
await
|
|
121181
|
+
await rm31(plDir, { recursive: true, force: true });
|
|
120889
121182
|
}
|
|
120890
121183
|
}
|
|
120891
121184
|
if (!opts.dryRun && await isEmptyDir(mpDir)) {
|
|
120892
|
-
await
|
|
121185
|
+
await rm31(mpDir, { recursive: true, force: true });
|
|
120893
121186
|
}
|
|
120894
121187
|
}
|
|
120895
121188
|
if (scanned === 0) {
|
|
@@ -120904,11 +121197,11 @@ function resolveClaudePluginCacheRoot(opts) {
|
|
|
120904
121197
|
if (explicitRoot)
|
|
120905
121198
|
return explicitRoot;
|
|
120906
121199
|
const home = opts.home ?? process.env[CLAUDE_PLUGIN_CACHE_HOME_ENV] ?? homedir();
|
|
120907
|
-
return
|
|
121200
|
+
return join133(home, ".claude", "plugins", "cache");
|
|
120908
121201
|
}
|
|
120909
121202
|
async function isEmptyDir(dir) {
|
|
120910
121203
|
try {
|
|
120911
|
-
const entries2 = await
|
|
121204
|
+
const entries2 = await readdir32(dir);
|
|
120912
121205
|
return entries2.length === 0;
|
|
120913
121206
|
} catch {
|
|
120914
121207
|
return false;
|
|
@@ -120958,7 +121251,7 @@ init_repoSourceRegistry();
|
|
|
120958
121251
|
init_writeLock();
|
|
120959
121252
|
import { execFile as execFile19 } from "node:child_process";
|
|
120960
121253
|
import { existsSync as existsSync34 } from "node:fs";
|
|
120961
|
-
import { lstat as lstat19, mkdir as mkdir42, readlink as readlink3, realpath as realpath16, rm as
|
|
121254
|
+
import { lstat as lstat19, mkdir as mkdir42, readlink as readlink3, realpath as realpath16, rm as rm32, symlink as symlink5 } from "node:fs/promises";
|
|
120962
121255
|
import { basename as basename12, dirname as dirname51, isAbsolute as isAbsolute23, relative as relative34, resolve as resolve43 } from "node:path";
|
|
120963
121256
|
import { promisify as promisify16 } from "node:util";
|
|
120964
121257
|
var execFileAsync5 = promisify16(execFile19);
|
|
@@ -121151,13 +121444,13 @@ async function cloneCheckout(input) {
|
|
|
121151
121444
|
try {
|
|
121152
121445
|
await clone(cloneArgs);
|
|
121153
121446
|
} catch (first) {
|
|
121154
|
-
await
|
|
121447
|
+
await rm32(target, { recursive: true, force: true });
|
|
121155
121448
|
try {
|
|
121156
121449
|
if (first instanceof GitProgressError && first.kind !== "failed")
|
|
121157
121450
|
throw first;
|
|
121158
121451
|
await clone(["clone", "--no-checkout", "--depth=1", input.remote, target]);
|
|
121159
121452
|
} catch (error) {
|
|
121160
|
-
await
|
|
121453
|
+
await rm32(target, { recursive: true, force: true });
|
|
121161
121454
|
const detail = error instanceof Error ? error.message : String(error);
|
|
121162
121455
|
throw new ContextError(ExitCode.ExternalToolError, `cannot clone registered repository: ${input.remote}`, {
|
|
121163
121456
|
category: ErrorCategory.ExternalToolFailed,
|
|
@@ -121184,7 +121477,7 @@ async function cloneCheckout(input) {
|
|
|
121184
121477
|
await verifyCheckout({ checkout: target, remote: input.remote, ref: input.ref, subpaths: input.subpaths });
|
|
121185
121478
|
return target;
|
|
121186
121479
|
} catch (error) {
|
|
121187
|
-
await
|
|
121480
|
+
await rm32(target, { recursive: true, force: true });
|
|
121188
121481
|
throw error;
|
|
121189
121482
|
}
|
|
121190
121483
|
}
|
|
@@ -121200,7 +121493,7 @@ async function bindLocalAlias(input) {
|
|
|
121200
121493
|
const actualReal = await realpath16(actual).catch(() => null);
|
|
121201
121494
|
if (actualReal !== null && actualReal === await realpath16(input.checkout))
|
|
121202
121495
|
return;
|
|
121203
|
-
await
|
|
121496
|
+
await rm32(alias);
|
|
121204
121497
|
} else {
|
|
121205
121498
|
const actual = await realpath16(alias);
|
|
121206
121499
|
if (actual === await realpath16(input.checkout))
|
|
@@ -121309,7 +121602,7 @@ init_src2();
|
|
|
121309
121602
|
init_documentCapture();
|
|
121310
121603
|
import { existsSync as existsSync35 } from "node:fs";
|
|
121311
121604
|
import { readFile as readFile108 } from "node:fs/promises";
|
|
121312
|
-
import { join as
|
|
121605
|
+
import { join as join135 } from "node:path";
|
|
121313
121606
|
|
|
121314
121607
|
// src/project/sourceCommandViews.ts
|
|
121315
121608
|
init_fileSourceOrigins();
|
|
@@ -121317,7 +121610,7 @@ init_documentSiteDetection();
|
|
|
121317
121610
|
init_workspace();
|
|
121318
121611
|
init_documentBatchManifest();
|
|
121319
121612
|
import { readFile as readFile107 } from "node:fs/promises";
|
|
121320
|
-
import { join as
|
|
121613
|
+
import { join as join134 } from "node:path";
|
|
121321
121614
|
function repoSourceAgentView(source2) {
|
|
121322
121615
|
return {
|
|
121323
121616
|
id: source2.id ?? source2.name,
|
|
@@ -121382,7 +121675,7 @@ async function fileSourceAgentViewWithNextAction(input) {
|
|
|
121382
121675
|
};
|
|
121383
121676
|
}
|
|
121384
121677
|
function documentSourceManifestPath(source2) {
|
|
121385
|
-
return source2.snapshot?.manifest ??
|
|
121678
|
+
return source2.snapshot?.manifest ?? join134(source2.materializedAt, "manifest.json");
|
|
121386
121679
|
}
|
|
121387
121680
|
async function fileSourceDocumentSiteHint(input) {
|
|
121388
121681
|
const detection = await detectDocumentSiteFiles({
|
|
@@ -121392,7 +121685,7 @@ async function fileSourceDocumentSiteHint(input) {
|
|
|
121392
121685
|
let snapshotConfigured = false;
|
|
121393
121686
|
const manifest = documentSourceManifestPath(input.source);
|
|
121394
121687
|
try {
|
|
121395
|
-
const parsed = parseDocumentSnapshotForSource(JSON.parse(await readFile107(
|
|
121688
|
+
const parsed = parseDocumentSnapshotForSource(JSON.parse(await readFile107(join134(input.projectRoot, manifest), "utf8")), input.source.name);
|
|
121396
121689
|
snapshotConfigured = manifestUsesMdxJsonDocs(parsed);
|
|
121397
121690
|
} catch {
|
|
121398
121691
|
snapshotConfigured = false;
|
|
@@ -121425,11 +121718,11 @@ async function larkSourceAgentViewWithNextAction(input) {
|
|
|
121425
121718
|
init_documentBatchManifest();
|
|
121426
121719
|
init_documentSnapshotFidelity();
|
|
121427
121720
|
function documentSourceManifestPath2(source2) {
|
|
121428
|
-
return source2.snapshot?.manifest ??
|
|
121721
|
+
return source2.snapshot?.manifest ?? join135(source2.materializedAt, "manifest.json");
|
|
121429
121722
|
}
|
|
121430
121723
|
async function documentSnapshotState(input) {
|
|
121431
121724
|
const manifest = documentSourceManifestPath2(input.source);
|
|
121432
|
-
const manifestPath =
|
|
121725
|
+
const manifestPath = join135(input.projectRoot, manifest);
|
|
121433
121726
|
if (!existsSync35(manifestPath)) {
|
|
121434
121727
|
return {
|
|
121435
121728
|
snapshotReady: false,
|
|
@@ -121508,7 +121801,7 @@ async function documentSnapshotState(input) {
|
|
|
121508
121801
|
const missing2 = [
|
|
121509
121802
|
...parsed.files.map((file) => file.path),
|
|
121510
121803
|
...(parsed.assets ?? []).filter((asset) => asset.content_hash !== undefined).map((asset) => asset.path)
|
|
121511
|
-
].find((path3) => !existsSync35(
|
|
121804
|
+
].find((path3) => !existsSync35(join135(input.projectRoot, input.source.materializedAt, path3)));
|
|
121512
121805
|
if (missing2 !== undefined) {
|
|
121513
121806
|
return {
|
|
121514
121807
|
snapshotReady: false,
|
|
@@ -121610,7 +121903,7 @@ init_exitCode();
|
|
|
121610
121903
|
var import_yaml59 = __toESM(require_dist(), 1);
|
|
121611
121904
|
import { createHash as createHash42 } from "node:crypto";
|
|
121612
121905
|
import { readFile as readFile109, realpath as realpath17 } from "node:fs/promises";
|
|
121613
|
-
import { basename as basename13, extname as extname15, isAbsolute as isAbsolute24, join as
|
|
121906
|
+
import { basename as basename13, extname as extname15, isAbsolute as isAbsolute24, join as join136, relative as relative35, resolve as resolve44 } from "node:path";
|
|
121614
121907
|
init_writeLock();
|
|
121615
121908
|
var SOURCE_NAME_PATTERN3 = /^[a-z0-9][a-z0-9._-]*$/u;
|
|
121616
121909
|
function isDateSourceNamespace(value) {
|
|
@@ -121706,7 +121999,7 @@ function assertSafeFileInclude(value) {
|
|
|
121706
121999
|
}
|
|
121707
122000
|
async function readRegistryDocument(projectRoot2, registryPath2) {
|
|
121708
122001
|
try {
|
|
121709
|
-
const content3 = await readFile109(
|
|
122002
|
+
const content3 = await readFile109(join136(projectRoot2, registryPath2), "utf8");
|
|
121710
122003
|
return content3.trim().length === 0 ? { sources: [] } : import_yaml59.default.parse(content3);
|
|
121711
122004
|
} catch (error) {
|
|
121712
122005
|
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
@@ -121796,7 +122089,7 @@ function flatRawSource(sources, name3) {
|
|
|
121796
122089
|
}
|
|
121797
122090
|
async function ensureOriginInstallRootIgnored(projectRoot2, kind) {
|
|
121798
122091
|
const line = `${fileSourceOriginInstallRoot(kind)}/`;
|
|
121799
|
-
const path3 =
|
|
122092
|
+
const path3 = join136(projectRoot2, ".gitignore");
|
|
121800
122093
|
let current3 = "";
|
|
121801
122094
|
try {
|
|
121802
122095
|
current3 = await readFile109(path3, "utf8");
|
|
@@ -121897,7 +122190,7 @@ async function addFileSourceUnlocked(input) {
|
|
|
121897
122190
|
sourceName: input.name
|
|
121898
122191
|
});
|
|
121899
122192
|
}
|
|
121900
|
-
await atomicWriteFile(
|
|
122193
|
+
await atomicWriteFile(join136(input.projectRoot, DEFAULT_FILE_SOURCES_REGISTRY_PATH), import_yaml59.default.stringify({ sources: nextSources }));
|
|
121901
122194
|
const gitignoreUpdated = origin !== undefined && await ensureOriginInstallRootIgnored(input.projectRoot, origin.kind);
|
|
121902
122195
|
const updated = await loadSourcesRegistry({ rootDir: input.projectRoot });
|
|
121903
122196
|
const entry = updated.files.find((source2) => source2.name === input.name || source2.id === input.name);
|
|
@@ -121958,7 +122251,7 @@ async function addLarkSourceUnlocked(input) {
|
|
|
121958
122251
|
const record6 = entry2;
|
|
121959
122252
|
return record6.name !== input.name && record6.id !== input.name;
|
|
121960
122253
|
}), nextEntry];
|
|
121961
|
-
await atomicWriteFile(
|
|
122254
|
+
await atomicWriteFile(join136(input.projectRoot, DEFAULT_LARK_SOURCES_REGISTRY_PATH), import_yaml59.default.stringify({ sources: nextSources }));
|
|
121962
122255
|
const updated = await loadSourcesRegistry({ rootDir: input.projectRoot });
|
|
121963
122256
|
const entry = updated.larks.find((source2) => source2.name === input.name || source2.id === input.name);
|
|
121964
122257
|
if (entry === undefined) {
|
|
@@ -121991,14 +122284,14 @@ init_errors3();
|
|
|
121991
122284
|
init_exitCode();
|
|
121992
122285
|
var import_yaml60 = __toESM(require_dist(), 1);
|
|
121993
122286
|
import { readFile as readFile110 } from "node:fs/promises";
|
|
121994
|
-
import { join as
|
|
121995
|
-
import { isDeepStrictEqual as
|
|
122287
|
+
import { join as join137 } from "node:path";
|
|
122288
|
+
import { isDeepStrictEqual as isDeepStrictEqual4 } from "node:util";
|
|
121996
122289
|
function identityKeys(entry) {
|
|
121997
122290
|
return new Set([entry.name, entry.id]);
|
|
121998
122291
|
}
|
|
121999
122292
|
async function createLarkBatchRegistration(projectRoot2, namespace) {
|
|
122000
122293
|
const registry2 = await loadSourcesRegistry({ rootDir: projectRoot2 });
|
|
122001
|
-
const registryPath2 =
|
|
122294
|
+
const registryPath2 = join137(projectRoot2, DEFAULT_LARK_SOURCES_REGISTRY_PATH);
|
|
122002
122295
|
let committedSources;
|
|
122003
122296
|
try {
|
|
122004
122297
|
const text12 = await readFile110(registryPath2, "utf8");
|
|
@@ -122102,7 +122395,7 @@ async function createLarkBatchRegistration(projectRoot2, namespace) {
|
|
|
122102
122395
|
modules: [...modules.values()]
|
|
122103
122396
|
};
|
|
122104
122397
|
const nextSources = batchIndex < 0 ? [...committedSources, batch] : committedSources.map((source2, index3) => index3 === batchIndex ? batch : source2);
|
|
122105
|
-
if (!
|
|
122398
|
+
if (!isDeepStrictEqual4(nextSources, committedSources)) {
|
|
122106
122399
|
await atomicWriteFile(registryPath2, import_yaml60.default.stringify({ sources: nextSources }));
|
|
122107
122400
|
committedSources = nextSources;
|
|
122108
122401
|
if (batchIndex < 0)
|
|
@@ -122120,7 +122413,7 @@ init_errors3();
|
|
|
122120
122413
|
init_exitCode();
|
|
122121
122414
|
import { createHash as createHash43 } from "node:crypto";
|
|
122122
122415
|
import { lstat as lstat20, readFile as readFile111 } from "node:fs/promises";
|
|
122123
|
-
import { join as
|
|
122416
|
+
import { join as join138, resolve as resolve45 } from "node:path";
|
|
122124
122417
|
var INPUT_SCHEMA = "context.source-batch.input.v1";
|
|
122125
122418
|
var STATE_SCHEMA = "context.source-batch.state.v1";
|
|
122126
122419
|
var RUNTIME_PARTS = [".tmp", "context-runtime", "source-batches"];
|
|
@@ -122171,14 +122464,14 @@ function paths(projectRoot2, jobId) {
|
|
|
122171
122464
|
throw journalError("source-batch-id-invalid", "Source batch checkpoint ID must contain exactly 32 lowercase hexadecimal characters.");
|
|
122172
122465
|
}
|
|
122173
122466
|
const directory = resolve45(projectRoot2, ...RUNTIME_PARTS, jobId);
|
|
122174
|
-
return { inputPath:
|
|
122467
|
+
return { inputPath: join138(directory, "input.json"), statePath: join138(directory, "state.json") };
|
|
122175
122468
|
}
|
|
122176
122469
|
async function assertJournalPath(projectRoot2, jobId, filename) {
|
|
122177
122470
|
paths(projectRoot2, jobId);
|
|
122178
122471
|
let current3 = resolve45(projectRoot2);
|
|
122179
122472
|
const parts = [...RUNTIME_PARTS, jobId, filename];
|
|
122180
122473
|
for (const [index3, part] of parts.entries()) {
|
|
122181
|
-
current3 =
|
|
122474
|
+
current3 = join138(current3, part);
|
|
122182
122475
|
let stat11;
|
|
122183
122476
|
try {
|
|
122184
122477
|
stat11 = await lstat20(current3);
|
|
@@ -122910,13 +123203,13 @@ init_exitCode();
|
|
|
122910
123203
|
|
|
122911
123204
|
// src/project/wikiDiscovery.ts
|
|
122912
123205
|
import { mkdir as mkdir44 } from "node:fs/promises";
|
|
122913
|
-
import { join as
|
|
123206
|
+
import { join as join140, relative as relative37 } from "node:path";
|
|
122914
123207
|
|
|
122915
123208
|
// src/project/wikiDiscoveryStore.ts
|
|
122916
123209
|
init_atomicWrite();
|
|
122917
123210
|
import { createHash as createHash44, randomUUID as randomUUID9 } from "node:crypto";
|
|
122918
|
-
import { link as link2, lstat as lstat21, mkdir as mkdir43, readFile as readFile112, readdir as
|
|
122919
|
-
import { join as
|
|
123211
|
+
import { link as link2, lstat as lstat21, mkdir as mkdir43, readFile as readFile112, readdir as readdir33, rm as rm33, writeFile as writeFile33 } from "node:fs/promises";
|
|
123212
|
+
import { join as join139, relative as relative36, resolve as resolve46, sep as sep11 } from "node:path";
|
|
122920
123213
|
function wikiDiscoveryDigest(value) {
|
|
122921
123214
|
return createHash44("sha256").update(value).digest("hex");
|
|
122922
123215
|
}
|
|
@@ -122930,7 +123223,7 @@ async function assertWikiDiscoveryPath(root2, path3) {
|
|
|
122930
123223
|
throw new WikiDiscoveryError("unsafe-checkpoint-path", false, "Discovery checkpoint must stay inside its workspace");
|
|
122931
123224
|
let current3 = base;
|
|
122932
123225
|
for (const part of parts) {
|
|
122933
|
-
current3 =
|
|
123226
|
+
current3 = join139(current3, part);
|
|
122934
123227
|
try {
|
|
122935
123228
|
if ((await lstat21(current3)).isSymbolicLink()) {
|
|
122936
123229
|
throw new WikiDiscoveryError("unsafe-checkpoint-path", false, "Discovery checkpoint paths must not contain symbolic links");
|
|
@@ -122959,12 +123252,12 @@ async function saveWikiDiscoveryJson(path3, value) {
|
|
|
122959
123252
|
}
|
|
122960
123253
|
async function loadWikiDiscoveryReceipts(directory) {
|
|
122961
123254
|
const result = new Map;
|
|
122962
|
-
await assertWikiDiscoveryPath(directory,
|
|
122963
|
-
await mkdir43(
|
|
122964
|
-
for (const file of await
|
|
123255
|
+
await assertWikiDiscoveryPath(directory, join139(directory, "pages"));
|
|
123256
|
+
await mkdir43(join139(directory, "pages"), { recursive: true });
|
|
123257
|
+
for (const file of await readdir33(join139(directory, "pages"))) {
|
|
122965
123258
|
if (!/^[a-f0-9]{64}\.json$/u.test(file))
|
|
122966
123259
|
continue;
|
|
122967
|
-
const value = await readWikiDiscoveryJson(
|
|
123260
|
+
const value = await readWikiDiscoveryJson(join139(directory, "pages", file));
|
|
122968
123261
|
if (!value || typeof value.parent_node_token !== "string" || value.page_token !== undefined && typeof value.page_token !== "string" || !["completed", "failed"].includes(value.status) || value.status === "completed" && (!value.page || !Array.isArray(value.page.nodes) || value.page.next_page_token !== undefined && typeof value.page.next_page_token !== "string") || value.status === "failed" && (!value.failure || typeof value.failure.retryable !== "boolean" || typeof value.failure.reason !== "string" || typeof value.failure.message !== "string") || `${wikiDiscoveryPageKey(value)}.json` !== file) {
|
|
122969
123262
|
throw new WikiDiscoveryError("checkpoint-invalid", false, "Discovery page checkpoint is invalid; preserve it for inspection");
|
|
122970
123263
|
}
|
|
@@ -122983,14 +123276,14 @@ function ownerRunning(pid) {
|
|
|
122983
123276
|
}
|
|
122984
123277
|
}
|
|
122985
123278
|
async function acquireWikiDiscoveryLease(directory) {
|
|
122986
|
-
const leases =
|
|
123279
|
+
const leases = join139(directory, "leases");
|
|
122987
123280
|
await assertWikiDiscoveryPath(directory, leases);
|
|
122988
123281
|
await mkdir43(leases, { recursive: true });
|
|
122989
123282
|
for (let attempt = 0;attempt < 8; attempt++) {
|
|
122990
|
-
const files = (await
|
|
123283
|
+
const files = (await readdir33(leases)).filter((file) => /^\d{12}\.json$/u.test(file)).sort();
|
|
122991
123284
|
const latest = files.at(-1);
|
|
122992
123285
|
if (latest) {
|
|
122993
|
-
const current3 = await readWikiDiscoveryJson(
|
|
123286
|
+
const current3 = await readWikiDiscoveryJson(join139(leases, latest));
|
|
122994
123287
|
if (!current3 || !Number.isSafeInteger(current3.pid) || current3.pid <= 0 || typeof current3.token !== "string" || typeof current3.released !== "boolean") {
|
|
122995
123288
|
throw new WikiDiscoveryError("checkpoint-invalid", false, "Discovery lease is invalid; preserve it for inspection");
|
|
122996
123289
|
}
|
|
@@ -122999,9 +123292,9 @@ async function acquireWikiDiscoveryLease(directory) {
|
|
|
122999
123292
|
}
|
|
123000
123293
|
}
|
|
123001
123294
|
const sequence = latest ? Number(latest.slice(0, 12)) + 1 : 1;
|
|
123002
|
-
const path3 =
|
|
123295
|
+
const path3 = join139(leases, `${String(sequence).padStart(12, "0")}.json`);
|
|
123003
123296
|
const owner = { pid: process.pid, token: randomUUID9(), released: false };
|
|
123004
|
-
const temporary =
|
|
123297
|
+
const temporary = join139(leases, `.lease-${owner.token}`);
|
|
123005
123298
|
await writeFile33(temporary, JSON.stringify(owner), { flag: "wx", mode: 384 });
|
|
123006
123299
|
try {
|
|
123007
123300
|
await link2(temporary, path3);
|
|
@@ -123010,7 +123303,7 @@ async function acquireWikiDiscoveryLease(directory) {
|
|
|
123010
123303
|
continue;
|
|
123011
123304
|
throw error;
|
|
123012
123305
|
} finally {
|
|
123013
|
-
await
|
|
123306
|
+
await rm33(temporary, { force: true });
|
|
123014
123307
|
}
|
|
123015
123308
|
return async () => {
|
|
123016
123309
|
await saveWikiDiscoveryJson(path3, { ...owner, released: true });
|
|
@@ -123126,7 +123419,7 @@ async function discoverLarkWiki(input) {
|
|
|
123126
123419
|
throw new WikiDiscoveryError("invalid-concurrency", false, "Wiki concurrency must be an integer from 1 to 4");
|
|
123127
123420
|
}
|
|
123128
123421
|
const jobId = wikiDiscoveryDigest(url);
|
|
123129
|
-
const directory =
|
|
123422
|
+
const directory = join140(input.projectRoot, ".tmp", "context-runtime", "wiki-discovery", jobId);
|
|
123130
123423
|
await assertWikiDiscoveryPath(input.projectRoot, directory);
|
|
123131
123424
|
await mkdir44(directory, { recursive: true });
|
|
123132
123425
|
const release = await acquireWikiDiscoveryLease(directory);
|
|
@@ -123138,7 +123431,7 @@ async function discoverLarkWiki(input) {
|
|
|
123138
123431
|
}
|
|
123139
123432
|
async function runDiscovery(input, job) {
|
|
123140
123433
|
const { directory, url, identity: identity2 } = job;
|
|
123141
|
-
const metadataPath =
|
|
123434
|
+
const metadataPath = join140(directory, "job.json");
|
|
123142
123435
|
let metadata = await readWikiDiscoveryJson(metadataPath);
|
|
123143
123436
|
if (metadata && (metadata.protocol !== "context.wiki-discovery.v1" || metadata.url !== url || metadata.identity !== identity2)) {
|
|
123144
123437
|
throw new WikiDiscoveryError("job-identity-mismatch", false, "Resume must preserve the discovery's original URL and identity");
|
|
@@ -123187,7 +123480,7 @@ async function runDiscovery(input, job) {
|
|
|
123187
123480
|
}
|
|
123188
123481
|
const key = wikiDiscoveryPageKey(cursor);
|
|
123189
123482
|
try {
|
|
123190
|
-
await saveWikiDiscoveryJson(
|
|
123483
|
+
await saveWikiDiscoveryJson(join140(directory, "pages", `${key}.json`), receipt2);
|
|
123191
123484
|
receipts.set(key, receipt2);
|
|
123192
123485
|
} catch {
|
|
123193
123486
|
checkpointError = "A discovery page could not be checkpointed; saved pages remain reusable and unsaved pages must be requested again";
|
|
@@ -123205,7 +123498,7 @@ async function finishDiscovery(input, state) {
|
|
|
123205
123498
|
const { directory, url, identity: identity2, jobId, metadata, view } = state;
|
|
123206
123499
|
let checkpointError = state.checkpointError;
|
|
123207
123500
|
let status = input.signal?.aborted ? "paused" : checkpointError || view.pending.length || view.failed.length || !metadata.root ? "partial" : "completed";
|
|
123208
|
-
const manifestPath =
|
|
123501
|
+
const manifestPath = join140(directory, "manifest.json");
|
|
123209
123502
|
try {
|
|
123210
123503
|
await saveWikiDiscoveryJson(manifestPath, {
|
|
123211
123504
|
protocol: "context.wiki-discovery.manifest.v1",
|
|
@@ -123385,8 +123678,8 @@ init_writeLock();
|
|
|
123385
123678
|
var import_yaml63 = __toESM(require_dist(), 1);
|
|
123386
123679
|
import { existsSync as existsSync36 } from "node:fs";
|
|
123387
123680
|
import { createHash as createHash45 } from "node:crypto";
|
|
123388
|
-
import { readFile as readFile113, readdir as
|
|
123389
|
-
import { isAbsolute as isAbsolute25, join as
|
|
123681
|
+
import { readFile as readFile113, readdir as readdir34, rm as rm34 } from "node:fs/promises";
|
|
123682
|
+
import { isAbsolute as isAbsolute25, join as join141, relative as relative38, resolve as resolve47, sep as sep12 } from "node:path";
|
|
123390
123683
|
function sourceIdentity(source2) {
|
|
123391
123684
|
if (source2.kind === "source.collection")
|
|
123392
123685
|
return;
|
|
@@ -123418,7 +123711,7 @@ function collectStrings(value, output) {
|
|
|
123418
123711
|
}
|
|
123419
123712
|
}
|
|
123420
123713
|
async function yamlReferences(input) {
|
|
123421
|
-
const absolutePath =
|
|
123714
|
+
const absolutePath = join141(input.projectRoot, input.path);
|
|
123422
123715
|
if (!existsSync36(absolutePath))
|
|
123423
123716
|
return false;
|
|
123424
123717
|
const parsed = import_yaml63.default.parse(await readFile113(absolutePath, "utf8"));
|
|
@@ -123567,7 +123860,7 @@ async function registryRemovalWrite(projectRoot2, source2) {
|
|
|
123567
123860
|
const path3 = registryPath2(source2.type);
|
|
123568
123861
|
if (path3 === null)
|
|
123569
123862
|
return;
|
|
123570
|
-
const absolutePath =
|
|
123863
|
+
const absolutePath = join141(projectRoot2, path3);
|
|
123571
123864
|
const document4 = existsSync36(absolutePath) ? import_yaml63.default.parse(await readFile113(absolutePath, "utf8")) : { sources: [] };
|
|
123572
123865
|
return {
|
|
123573
123866
|
path: absolutePath,
|
|
@@ -123586,7 +123879,7 @@ function safeManagedMaterializedPath(projectRoot2, source2) {
|
|
|
123586
123879
|
return absolute;
|
|
123587
123880
|
}
|
|
123588
123881
|
function safeManagedManifestPath(projectRoot2, source2) {
|
|
123589
|
-
const manifest = source2.manifest ??
|
|
123882
|
+
const manifest = source2.manifest ?? join141(source2.materializedAt, "manifest.json");
|
|
123590
123883
|
if (isAbsolute25(manifest))
|
|
123591
123884
|
throw unsafeOwnership(source2, manifest);
|
|
123592
123885
|
const absolute = resolve47(projectRoot2, manifest);
|
|
@@ -123748,7 +124041,7 @@ function publicRemovalResult(plan, action) {
|
|
|
123748
124041
|
};
|
|
123749
124042
|
}
|
|
123750
124043
|
async function pruneExtractRuntime(projectRoot2, source2) {
|
|
123751
|
-
const fingerprintPath =
|
|
124044
|
+
const fingerprintPath = join141(projectRoot2, ".tmp/context-runtime/extract/source-fingerprints.json");
|
|
123752
124045
|
const removedPhaseIds = new Set;
|
|
123753
124046
|
if (existsSync36(fingerprintPath)) {
|
|
123754
124047
|
const parsed = JSON.parse(await readFile113(fingerprintPath, "utf8"));
|
|
@@ -123765,14 +124058,14 @@ async function pruneExtractRuntime(projectRoot2, source2) {
|
|
|
123765
124058
|
await atomicWriteFile(fingerprintPath, `${JSON.stringify({ ...parsed, phases: next2 }, null, 2)}
|
|
123766
124059
|
`);
|
|
123767
124060
|
}
|
|
123768
|
-
const phaseOwnershipPath =
|
|
124061
|
+
const phaseOwnershipPath = join141(projectRoot2, ".tmp/context-runtime/extract/custom-phase-candidates.json");
|
|
123769
124062
|
if (existsSync36(phaseOwnershipPath) && removedPhaseIds.size > 0) {
|
|
123770
124063
|
const parsed = JSON.parse(await readFile113(phaseOwnershipPath, "utf8"));
|
|
123771
124064
|
const phases = Object.fromEntries(Object.entries(parsed.phases ?? {}).filter(([phaseId]) => !removedPhaseIds.has(phaseId)));
|
|
123772
124065
|
await atomicWriteFile(phaseOwnershipPath, `${JSON.stringify({ ...parsed, phases }, null, 2)}
|
|
123773
124066
|
`);
|
|
123774
124067
|
}
|
|
123775
|
-
const symbolPath =
|
|
124068
|
+
const symbolPath = join141(projectRoot2, ".tmp/context-runtime/extract/source-symbols.json");
|
|
123776
124069
|
if (existsSync36(symbolPath)) {
|
|
123777
124070
|
const parsed = JSON.parse(await readFile113(symbolPath, "utf8"));
|
|
123778
124071
|
const symbols = Array.isArray(parsed.symbols) ? parsed.symbols.filter((entry) => entry === null || typeof entry !== "object" || Array.isArray(entry) || entry.source !== source2.name) : [];
|
|
@@ -123780,12 +124073,12 @@ async function pruneExtractRuntime(projectRoot2, source2) {
|
|
|
123780
124073
|
await atomicWriteFile(symbolPath, `${JSON.stringify({ ...parsed, phaseFingerprints, symbols }, null, 2)}
|
|
123781
124074
|
`);
|
|
123782
124075
|
}
|
|
123783
|
-
const snapshotRoot =
|
|
124076
|
+
const snapshotRoot = join141(projectRoot2, ".tmp/context-runtime/extract/candidates");
|
|
123784
124077
|
const visit4 = async (directory) => {
|
|
123785
124078
|
if (!existsSync36(directory))
|
|
123786
124079
|
return;
|
|
123787
|
-
for (const entry of await
|
|
123788
|
-
const path3 =
|
|
124080
|
+
for (const entry of await readdir34(directory, { withFileTypes: true })) {
|
|
124081
|
+
const path3 = join141(directory, entry.name);
|
|
123789
124082
|
if (entry.isDirectory()) {
|
|
123790
124083
|
await visit4(path3);
|
|
123791
124084
|
continue;
|
|
@@ -123796,7 +124089,7 @@ async function pruneExtractRuntime(projectRoot2, source2) {
|
|
|
123796
124089
|
const parsed = JSON.parse(await readFile113(path3, "utf8"));
|
|
123797
124090
|
const refs = Array.isArray(parsed.source_refs) ? parsed.source_refs : [];
|
|
123798
124091
|
if (parsed.source === source2.name || refs.some((ref2) => typeof ref2 === "string" && stringReferencesSource(ref2, source2))) {
|
|
123799
|
-
await
|
|
124092
|
+
await rm34(path3, { force: true });
|
|
123800
124093
|
}
|
|
123801
124094
|
} catch {}
|
|
123802
124095
|
}
|
|
@@ -123835,7 +124128,7 @@ async function removeProjectSource(input) {
|
|
|
123835
124128
|
});
|
|
123836
124129
|
}
|
|
123837
124130
|
await applyAtomicFileBatch({
|
|
123838
|
-
transactionRoot:
|
|
124131
|
+
transactionRoot: join141(input.projectRoot, ".tmp", "context-runtime", "source-remove-transactions"),
|
|
123839
124132
|
writes: [...plan.registryWrite === undefined ? [] : [plan.registryWrite], ...plan.manifestWrite !== undefined ? [plan.manifestWrite] : []],
|
|
123840
124133
|
removals: plan.absoluteRemovals
|
|
123841
124134
|
});
|
|
@@ -124036,7 +124329,7 @@ init_sourceInputMutation();
|
|
|
124036
124329
|
init_writeLock();
|
|
124037
124330
|
import { execFile as execFile20 } from "node:child_process";
|
|
124038
124331
|
import { promisify as promisify17 } from "node:util";
|
|
124039
|
-
import { join as
|
|
124332
|
+
import { join as join142 } from "node:path";
|
|
124040
124333
|
var exec6 = promisify17(execFile20);
|
|
124041
124334
|
var requestSchema3 = exports_external.object({ type: exports_external.enum(["file", "lark"]), name: exports_external.string().min(1), commit: exports_external.string().min(1).optional() }).strict();
|
|
124042
124335
|
async function restoreDocumentSnapshot(projectRoot2, value) {
|
|
@@ -124128,8 +124421,8 @@ async function restoreDocumentSnapshot(projectRoot2, value) {
|
|
|
124128
124421
|
const removals = [...previous3?.files ?? [], ...previous3?.assets ?? []].map((file) => `${source2.materializedAt}/${file.path}`).filter((path3) => !selected.files.has(path3) && !renderDocumentManifestFile(next2).includes(path3.slice(source2.materializedAt.length + 1)));
|
|
124129
124422
|
const removalTargets = await Promise.all(removals.map((path3) => safeProjectTarget(projectRoot2, path3)));
|
|
124130
124423
|
await applyAtomicFileBatch({
|
|
124131
|
-
transactionRoot:
|
|
124132
|
-
writes: [...selected.files].map(([path3, bytes]) => ({ path:
|
|
124424
|
+
transactionRoot: join142(projectRoot2, ".tmp/context-runtime/capture-transactions"),
|
|
124425
|
+
writes: [...selected.files].map(([path3, bytes]) => ({ path: join142(projectRoot2, path3), bytes })).concat([
|
|
124133
124426
|
{ path: manifestTarget, bytes: Buffer.from(renderDocumentManifestFile(next2)) }
|
|
124134
124427
|
]),
|
|
124135
124428
|
removals: removalTargets
|
|
@@ -124663,8 +124956,8 @@ init_cliFeedback();
|
|
|
124663
124956
|
init_exitCode();
|
|
124664
124957
|
var import_yaml66 = __toESM(require_dist(), 1);
|
|
124665
124958
|
import { constants as constants6, existsSync as existsSync37 } from "node:fs";
|
|
124666
|
-
import { lstat as lstat22, open as open5, readdir as
|
|
124667
|
-
import { dirname as dirname52, join as
|
|
124959
|
+
import { lstat as lstat22, open as open5, readdir as readdir35 } from "node:fs/promises";
|
|
124960
|
+
import { dirname as dirname52, join as join144, resolve as resolve50 } from "node:path";
|
|
124668
124961
|
import { fileURLToPath as fileURLToPath10 } from "node:url";
|
|
124669
124962
|
function bundledSkillRoot() {
|
|
124670
124963
|
const directory = dirname52(fileURLToPath10(import.meta.url));
|
|
@@ -124691,10 +124984,10 @@ async function listProductionSkills(root2) {
|
|
|
124691
124984
|
}
|
|
124692
124985
|
}
|
|
124693
124986
|
async function readProductionSkills(root2) {
|
|
124694
|
-
const entries2 = (await
|
|
124987
|
+
const entries2 = (await readdir35(root2, { withFileTypes: true })).filter((entry) => entry.isDirectory()).sort((a2, b) => a2.name < b.name ? -1 : a2.name > b.name ? 1 : 0);
|
|
124695
124988
|
const skills = [];
|
|
124696
124989
|
for (const directory of entries2) {
|
|
124697
|
-
const entry =
|
|
124990
|
+
const entry = join144(root2, directory.name, "SKILL.md");
|
|
124698
124991
|
if (!(await lstat22(entry)).isFile())
|
|
124699
124992
|
throw new TypeError(`Skill entry must be a regular file: ${entry}`);
|
|
124700
124993
|
const handle3 = await open5(entry, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
|
|
@@ -125108,8 +125401,8 @@ init_cliFeedback();
|
|
|
125108
125401
|
init_errors3();
|
|
125109
125402
|
init_exitCode();
|
|
125110
125403
|
import { createHash as createHash46 } from "node:crypto";
|
|
125111
|
-
import { cp as cp3, lstat as lstat23, mkdir as mkdir45, mkdtemp as mkdtemp7, readFile as readFile119, readdir as
|
|
125112
|
-
import { dirname as dirname54, join as
|
|
125404
|
+
import { cp as cp3, lstat as lstat23, mkdir as mkdir45, mkdtemp as mkdtemp7, readFile as readFile119, readdir as readdir36, rename as rename12, rm as rm35, writeFile as writeFile34 } from "node:fs/promises";
|
|
125405
|
+
import { dirname as dirname54, join as join145, resolve as resolve52 } from "node:path";
|
|
125113
125406
|
var MARKER = ".context-skill-install.json";
|
|
125114
125407
|
function conflict(path3) {
|
|
125115
125408
|
throw new ContextError(ExitCode.UserError, `Local skill install conflict: ${path3}`, {
|
|
@@ -125137,10 +125430,10 @@ async function checkParents(path3) {
|
|
|
125137
125430
|
async function digest9(root2) {
|
|
125138
125431
|
const hash5 = createHash46("sha256");
|
|
125139
125432
|
async function visit4(dir, prefix) {
|
|
125140
|
-
for (const name3 of (await
|
|
125433
|
+
for (const name3 of (await readdir36(dir)).sort()) {
|
|
125141
125434
|
if (!prefix && name3 === MARKER)
|
|
125142
125435
|
continue;
|
|
125143
|
-
const path3 =
|
|
125436
|
+
const path3 = join145(dir, name3);
|
|
125144
125437
|
const entry = await lstat23(path3);
|
|
125145
125438
|
if (entry.isSymbolicLink())
|
|
125146
125439
|
conflict(path3);
|
|
@@ -125159,7 +125452,7 @@ async function digest9(root2) {
|
|
|
125159
125452
|
async function assertOwnedDirectory(target, existing) {
|
|
125160
125453
|
if (!existing.isDirectory() || existing.isSymbolicLink())
|
|
125161
125454
|
conflict(target);
|
|
125162
|
-
const markerPath =
|
|
125455
|
+
const markerPath = join145(target, MARKER);
|
|
125163
125456
|
if (!(await stat11(markerPath))?.isFile())
|
|
125164
125457
|
conflict(target);
|
|
125165
125458
|
let marker;
|
|
@@ -125175,24 +125468,24 @@ async function installLocalSkills(root2, path3, dryRun, agent) {
|
|
|
125175
125468
|
if (!path3.trim())
|
|
125176
125469
|
conflict("--local requires a non-empty path");
|
|
125177
125470
|
const targetRoot = resolve52(path3);
|
|
125178
|
-
const skillsRoot =
|
|
125471
|
+
const skillsRoot = join145(targetRoot, "skills");
|
|
125179
125472
|
await checkParents(skillsRoot);
|
|
125180
|
-
const sourceRoot =
|
|
125473
|
+
const sourceRoot = join145(root2, "skills");
|
|
125181
125474
|
const commandPlans = [];
|
|
125182
125475
|
const commandEntries = new Set;
|
|
125183
125476
|
if (agent === "claude" || agent === "cursor") {
|
|
125184
|
-
for (const name3 of await
|
|
125477
|
+
for (const name3 of await readdir36(join145(root2, "claude", "commands"))) {
|
|
125185
125478
|
if (name3.endsWith(".md"))
|
|
125186
125479
|
commandEntries.add(name3.slice(0, -3));
|
|
125187
125480
|
}
|
|
125188
|
-
const commandsRoot =
|
|
125481
|
+
const commandsRoot = join145(targetRoot, "commands");
|
|
125189
125482
|
await checkParents(commandsRoot);
|
|
125190
|
-
for (const entry of await
|
|
125483
|
+
for (const entry of await readdir36(join145(root2, agent, "commands"), { withFileTypes: true })) {
|
|
125191
125484
|
if (!entry.isFile() || !entry.name.endsWith(".md"))
|
|
125192
125485
|
continue;
|
|
125193
|
-
const content3 = await readFile119(
|
|
125194
|
-
const target =
|
|
125195
|
-
const marker =
|
|
125486
|
+
const content3 = await readFile119(join145(root2, agent, "commands", entry.name), "utf8");
|
|
125487
|
+
const target = join145(commandsRoot, entry.name);
|
|
125488
|
+
const marker = join145(commandsRoot, `.context-${entry.name}.json`);
|
|
125196
125489
|
for (const file of [target, marker]) {
|
|
125197
125490
|
const existing = await stat11(file);
|
|
125198
125491
|
if (existing && (!existing.isFile() || existing.isSymbolicLink()))
|
|
@@ -125213,14 +125506,14 @@ async function installLocalSkills(root2, path3, dryRun, agent) {
|
|
|
125213
125506
|
commandPlans.push({ name: entry.name, target, marker, content: content3, hash: createHash46("sha256").update(content3).digest("hex") });
|
|
125214
125507
|
}
|
|
125215
125508
|
if (!commandPlans.length)
|
|
125216
|
-
conflict(
|
|
125509
|
+
conflict(join145(root2, agent, "commands"));
|
|
125217
125510
|
}
|
|
125218
125511
|
const plans = [];
|
|
125219
|
-
for (const entry of (await
|
|
125220
|
-
if (!entry.isDirectory() || !await stat11(
|
|
125512
|
+
for (const entry of (await readdir36(sourceRoot, { withFileTypes: true })).sort((a2, b) => a2.name.localeCompare(b.name))) {
|
|
125513
|
+
if (!entry.isDirectory() || !await stat11(join145(sourceRoot, entry.name, "SKILL.md")))
|
|
125221
125514
|
continue;
|
|
125222
|
-
const source2 =
|
|
125223
|
-
const target =
|
|
125515
|
+
const source2 = join145(sourceRoot, entry.name);
|
|
125516
|
+
const target = join145(skillsRoot, entry.name);
|
|
125224
125517
|
if (commandEntries.has(entry.name) && !["context-plan", "context-repo-content"].includes(entry.name)) {
|
|
125225
125518
|
if (await stat11(target))
|
|
125226
125519
|
conflict(`${target} (use a fresh host directory to avoid duplicate command/skill entries)`);
|
|
@@ -125234,16 +125527,16 @@ async function installLocalSkills(root2, path3, dryRun, agent) {
|
|
|
125234
125527
|
if (!plans.length)
|
|
125235
125528
|
conflict(sourceRoot);
|
|
125236
125529
|
const resourcePlans = [];
|
|
125237
|
-
const resourcesRoot =
|
|
125530
|
+
const resourcesRoot = join145(targetRoot, "resources");
|
|
125238
125531
|
if (agent === "claude" || agent === "cursor") {
|
|
125239
|
-
const resourceSource =
|
|
125532
|
+
const resourceSource = join145(root2, agent, "resources");
|
|
125240
125533
|
if (await stat11(resourceSource)) {
|
|
125241
125534
|
await checkParents(resourcesRoot);
|
|
125242
|
-
for (const entry of (await
|
|
125535
|
+
for (const entry of (await readdir36(resourceSource, { withFileTypes: true })).sort((a2, b) => a2.name.localeCompare(b.name))) {
|
|
125243
125536
|
if (!entry.isDirectory())
|
|
125244
125537
|
continue;
|
|
125245
|
-
const source2 =
|
|
125246
|
-
const target =
|
|
125538
|
+
const source2 = join145(resourceSource, entry.name);
|
|
125539
|
+
const target = join145(resourcesRoot, entry.name);
|
|
125247
125540
|
const existing = await stat11(target);
|
|
125248
125541
|
if (existing)
|
|
125249
125542
|
await assertOwnedDirectory(target, existing);
|
|
@@ -125257,14 +125550,14 @@ async function installLocalSkills(root2, path3, dryRun, agent) {
|
|
|
125257
125550
|
await mkdir45(resourcesRoot, { recursive: true });
|
|
125258
125551
|
for (const plan of [...plans, ...resourcePlans]) {
|
|
125259
125552
|
const resource = resourcePlans.includes(plan);
|
|
125260
|
-
const staging = await mkdtemp7(
|
|
125261
|
-
const candidate =
|
|
125262
|
-
const previous3 =
|
|
125553
|
+
const staging = await mkdtemp7(join145(dirname54(plan.target), ".context-install-"));
|
|
125554
|
+
const candidate = join145(staging, "candidate");
|
|
125555
|
+
const previous3 = join145(staging, "previous");
|
|
125263
125556
|
let moved = false;
|
|
125264
125557
|
try {
|
|
125265
125558
|
await cp3(plan.source, candidate, { recursive: true });
|
|
125266
125559
|
if (!resource && (agent === "claude" || agent === "cursor" && ["context-plan", "context-repo-content"].includes(plan.name))) {
|
|
125267
|
-
const skillFile =
|
|
125560
|
+
const skillFile = join145(candidate, "SKILL.md");
|
|
125268
125561
|
const content3 = await readFile119(skillFile, "utf8");
|
|
125269
125562
|
const parts = /^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/.exec(content3);
|
|
125270
125563
|
if (parts && (["context-plan", "context-repo-content"].includes(plan.name) || /^\s*context-public-entry:\s*["']?false["']?\s*$/mu.test(parts[2]))) {
|
|
@@ -125273,7 +125566,7 @@ async function installLocalSkills(root2, path3, dryRun, agent) {
|
|
|
125273
125566
|
${frontmatter2}${parts[3]}${content3.slice(parts[0].length)}`);
|
|
125274
125567
|
}
|
|
125275
125568
|
}
|
|
125276
|
-
await writeFile34(
|
|
125569
|
+
await writeFile34(join145(candidate, MARKER), JSON.stringify({ owner: "context-plugin-local", digest: await digest9(candidate) }) + `
|
|
125277
125570
|
`);
|
|
125278
125571
|
if (plan.exists) {
|
|
125279
125572
|
await rename12(plan.target, previous3);
|
|
@@ -125286,7 +125579,7 @@ ${frontmatter2}${parts[3]}${content3.slice(parts[0].length)}`);
|
|
|
125286
125579
|
await rename12(previous3, plan.target);
|
|
125287
125580
|
throw error;
|
|
125288
125581
|
}
|
|
125289
|
-
await
|
|
125582
|
+
await rm35(staging, { recursive: true, force: true });
|
|
125290
125583
|
} catch (error) {
|
|
125291
125584
|
throw new ContextError(ExitCode.WorkspaceStateError, `Local skill installation failed: ${plan.target}`, {
|
|
125292
125585
|
category: ErrorCategory.WorkspaceStateInvalid,
|
|
@@ -125297,13 +125590,13 @@ ${frontmatter2}${parts[3]}${content3.slice(parts[0].length)}`);
|
|
|
125297
125590
|
}
|
|
125298
125591
|
for (const command3 of commandPlans) {
|
|
125299
125592
|
await mkdir45(dirname54(command3.target), { recursive: true });
|
|
125300
|
-
const staging = await mkdtemp7(
|
|
125301
|
-
await writeFile34(
|
|
125302
|
-
await writeFile34(
|
|
125593
|
+
const staging = await mkdtemp7(join145(dirname54(command3.target), ".context-install-"));
|
|
125594
|
+
await writeFile34(join145(staging, "command"), command3.content);
|
|
125595
|
+
await writeFile34(join145(staging, "marker"), JSON.stringify({ owner: "context-plugin-local", digest: command3.hash }) + `
|
|
125303
125596
|
`);
|
|
125304
|
-
await rename12(
|
|
125305
|
-
await rename12(
|
|
125306
|
-
await
|
|
125597
|
+
await rename12(join145(staging, "command"), command3.target);
|
|
125598
|
+
await rename12(join145(staging, "marker"), command3.marker);
|
|
125599
|
+
await rm35(staging, { recursive: true, force: true });
|
|
125307
125600
|
}
|
|
125308
125601
|
}
|
|
125309
125602
|
return formatFeedback({
|
|
@@ -125327,10 +125620,10 @@ init_cliFeedback();
|
|
|
125327
125620
|
init_errors3();
|
|
125328
125621
|
init_exitCode();
|
|
125329
125622
|
import { lstat as lstat24 } from "node:fs/promises";
|
|
125330
|
-
import { join as
|
|
125623
|
+
import { join as join146, resolve as resolve53 } from "node:path";
|
|
125331
125624
|
var HOST_DIRS = { claude: ".claude", cursor: ".cursor", codex: ".agents" };
|
|
125332
125625
|
async function detectLocalAgent(agent, repo) {
|
|
125333
|
-
const path3 =
|
|
125626
|
+
const path3 = join146(repo, HOST_DIRS[agent]);
|
|
125334
125627
|
try {
|
|
125335
125628
|
const entry = await lstat24(path3);
|
|
125336
125629
|
if (!entry.isDirectory() || entry.isSymbolicLink()) {
|
|
@@ -125355,7 +125648,7 @@ async function installAutoLocalSkills(root2, path3, dryRun, detect = detectLocal
|
|
|
125355
125648
|
if (selectedAgent ? selectedAgent === "all" || agent === selectedAgent : await detect(agent, repo))
|
|
125356
125649
|
agents.push(agent);
|
|
125357
125650
|
}
|
|
125358
|
-
const targets = agents.length ? agents.map((agent) => ({ agent, path:
|
|
125651
|
+
const targets = agents.length ? agents.map((agent) => ({ agent, path: join146(repo, HOST_DIRS[agent]) })) : [{ path: join146(repo, ".agents") }];
|
|
125359
125652
|
const previews = [];
|
|
125360
125653
|
for (const target of targets)
|
|
125361
125654
|
previews.push(await installLocalSkills(root2, target.path, true, target.agent));
|
|
@@ -125388,7 +125681,7 @@ init_cliFeedback();
|
|
|
125388
125681
|
init_errors3();
|
|
125389
125682
|
init_exitCode();
|
|
125390
125683
|
import { existsSync as existsSync40 } from "node:fs";
|
|
125391
|
-
import { dirname as dirname56, join as
|
|
125684
|
+
import { dirname as dirname56, join as join148, resolve as resolve54 } from "node:path";
|
|
125392
125685
|
import { fileURLToPath as fileURLToPath11 } from "node:url";
|
|
125393
125686
|
|
|
125394
125687
|
// src/project/pluginInstallTargets.ts
|
|
@@ -125397,9 +125690,9 @@ init_errors3();
|
|
|
125397
125690
|
init_exitCode();
|
|
125398
125691
|
import { execFile as execFile21 } from "node:child_process";
|
|
125399
125692
|
import { existsSync as existsSync39 } from "node:fs";
|
|
125400
|
-
import { cp as cp4, mkdir as mkdir46, readdir as
|
|
125693
|
+
import { cp as cp4, mkdir as mkdir46, readdir as readdir37, readFile as readFile120, rename as rename13, rm as rm36, writeFile as writeFile35 } from "node:fs/promises";
|
|
125401
125694
|
import { homedir as homedir2 } from "node:os";
|
|
125402
|
-
import { dirname as dirname55, join as
|
|
125695
|
+
import { dirname as dirname55, join as join147 } from "node:path";
|
|
125403
125696
|
import { promisify as promisify18 } from "node:util";
|
|
125404
125697
|
var execFileAsync6 = promisify18(execFile21);
|
|
125405
125698
|
var MARKETPLACE_NAME = "c4a";
|
|
@@ -125453,23 +125746,23 @@ async function claudePluginInstalled(pluginId) {
|
|
|
125453
125746
|
}
|
|
125454
125747
|
}
|
|
125455
125748
|
function codexHome() {
|
|
125456
|
-
return process.env.CODEX_HOME?.trim() ||
|
|
125749
|
+
return process.env.CODEX_HOME?.trim() || join147(homedir2(), ".codex");
|
|
125457
125750
|
}
|
|
125458
125751
|
function claudePluginCacheRoot() {
|
|
125459
125752
|
const explicitRoot = process.env[CLAUDE_PLUGIN_CACHE_ROOT_ENV2]?.trim();
|
|
125460
125753
|
if (explicitRoot)
|
|
125461
125754
|
return explicitRoot;
|
|
125462
125755
|
const home = process.env[CLAUDE_PLUGIN_CACHE_HOME_ENV2]?.trim() || homedir2();
|
|
125463
|
-
return
|
|
125756
|
+
return join147(home, ".claude", "plugins", "cache");
|
|
125464
125757
|
}
|
|
125465
125758
|
function sharedSkillsRoot() {
|
|
125466
|
-
return process.env[SHARED_SKILLS_ROOT_ENV]?.trim() ||
|
|
125759
|
+
return process.env[SHARED_SKILLS_ROOT_ENV]?.trim() || join147(homedir2(), ".agents", "skills");
|
|
125467
125760
|
}
|
|
125468
125761
|
function claudeSkillsRoot() {
|
|
125469
|
-
return process.env[CLAUDE_SKILLS_ROOT_ENV]?.trim() ||
|
|
125762
|
+
return process.env[CLAUDE_SKILLS_ROOT_ENV]?.trim() || join147(homedir2(), ".claude", "skills");
|
|
125470
125763
|
}
|
|
125471
125764
|
function cursorPluginRoot() {
|
|
125472
|
-
return process.env[CURSOR_PLUGIN_ROOT_ENV]?.trim() ||
|
|
125765
|
+
return process.env[CURSOR_PLUGIN_ROOT_ENV]?.trim() || join147(homedir2(), ".cursor", "plugins", "local", PLUGIN_NAME);
|
|
125473
125766
|
}
|
|
125474
125767
|
function blockHeader(line) {
|
|
125475
125768
|
const match = line.match(/^\s*\[([^\]]+)\]\s*$/u);
|
|
@@ -125520,7 +125813,7 @@ function pruneLegacyCodexConfigContent(content3) {
|
|
|
125520
125813
|
`), removed };
|
|
125521
125814
|
}
|
|
125522
125815
|
async function pruneLegacyCodexConfig(dryRun, steps) {
|
|
125523
|
-
const configPath =
|
|
125816
|
+
const configPath = join147(codexHome(), "config.toml");
|
|
125524
125817
|
const current3 = await readFile120(configPath, "utf8").catch(() => "");
|
|
125525
125818
|
if (!current3)
|
|
125526
125819
|
return;
|
|
@@ -125537,10 +125830,10 @@ async function pruneLegacyCodexConfig(dryRun, steps) {
|
|
|
125537
125830
|
}
|
|
125538
125831
|
}
|
|
125539
125832
|
async function pruneCodexPluginCacheForName(pluginName, keepVersion, dryRun, steps) {
|
|
125540
|
-
const cacheRoot =
|
|
125833
|
+
const cacheRoot = join147(codexHome(), "plugins", "cache", MARKETPLACE_NAME, pluginName);
|
|
125541
125834
|
if (!existsSync39(cacheRoot))
|
|
125542
125835
|
return;
|
|
125543
|
-
const versions = (await
|
|
125836
|
+
const versions = (await readdir37(cacheRoot, { withFileTypes: true }).catch(() => [])).filter((entry) => entry.isDirectory() && entry.name !== keepVersion).map((entry) => entry.name).sort();
|
|
125544
125837
|
if (versions.length === 0)
|
|
125545
125838
|
return;
|
|
125546
125839
|
steps.push({
|
|
@@ -125549,7 +125842,7 @@ async function pruneCodexPluginCacheForName(pluginName, keepVersion, dryRun, ste
|
|
|
125549
125842
|
status: dryRun ? "planned" : "ran"
|
|
125550
125843
|
});
|
|
125551
125844
|
if (!dryRun)
|
|
125552
|
-
await Promise.all(versions.map((version3) =>
|
|
125845
|
+
await Promise.all(versions.map((version3) => rm36(join147(cacheRoot, version3), { recursive: true, force: true })));
|
|
125553
125846
|
}
|
|
125554
125847
|
async function pruneCodexPluginCache(currentVersion, dryRun, steps) {
|
|
125555
125848
|
await pruneCodexPluginCacheForName(PLUGIN_NAME, currentVersion, dryRun, steps);
|
|
@@ -125559,7 +125852,7 @@ async function pruneCodexPluginCache(currentVersion, dryRun, steps) {
|
|
|
125559
125852
|
}
|
|
125560
125853
|
async function isEmptyDir2(dir) {
|
|
125561
125854
|
try {
|
|
125562
|
-
return (await
|
|
125855
|
+
return (await readdir37(dir)).length === 0;
|
|
125563
125856
|
} catch {
|
|
125564
125857
|
return false;
|
|
125565
125858
|
}
|
|
@@ -125569,31 +125862,31 @@ async function pruneClaudeOrphanContextCache(dryRun, steps) {
|
|
|
125569
125862
|
if (!existsSync39(cacheRoot))
|
|
125570
125863
|
return;
|
|
125571
125864
|
const removed = [];
|
|
125572
|
-
const marketplaces = await
|
|
125865
|
+
const marketplaces = await readdir37(cacheRoot, { withFileTypes: true }).catch(() => []);
|
|
125573
125866
|
for (const marketplace of marketplaces) {
|
|
125574
125867
|
if (!marketplace.isDirectory())
|
|
125575
125868
|
continue;
|
|
125576
|
-
const pluginDir =
|
|
125869
|
+
const pluginDir = join147(cacheRoot, marketplace.name, PLUGIN_NAME);
|
|
125577
125870
|
if (!existsSync39(pluginDir))
|
|
125578
125871
|
continue;
|
|
125579
|
-
const versions = await
|
|
125872
|
+
const versions = await readdir37(pluginDir, { withFileTypes: true }).catch(() => []);
|
|
125580
125873
|
for (const version3 of versions) {
|
|
125581
125874
|
if (!version3.isDirectory())
|
|
125582
125875
|
continue;
|
|
125583
|
-
const versionDir =
|
|
125584
|
-
if (!existsSync39(
|
|
125876
|
+
const versionDir = join147(pluginDir, version3.name);
|
|
125877
|
+
if (!existsSync39(join147(versionDir, ORPHAN_MARKER2)))
|
|
125585
125878
|
continue;
|
|
125586
125879
|
removed.push(`${marketplace.name}/${PLUGIN_NAME}/${version3.name}`);
|
|
125587
125880
|
if (!dryRun) {
|
|
125588
|
-
await
|
|
125881
|
+
await rm36(versionDir, { recursive: true, force: true });
|
|
125589
125882
|
}
|
|
125590
125883
|
}
|
|
125591
125884
|
if (!dryRun && await isEmptyDir2(pluginDir)) {
|
|
125592
|
-
await
|
|
125885
|
+
await rm36(pluginDir, { recursive: true, force: true });
|
|
125593
125886
|
}
|
|
125594
|
-
const marketplaceDir =
|
|
125887
|
+
const marketplaceDir = join147(cacheRoot, marketplace.name);
|
|
125595
125888
|
if (!dryRun && await isEmptyDir2(marketplaceDir)) {
|
|
125596
|
-
await
|
|
125889
|
+
await rm36(marketplaceDir, { recursive: true, force: true });
|
|
125597
125890
|
}
|
|
125598
125891
|
}
|
|
125599
125892
|
if (removed.length > 0) {
|
|
@@ -125612,12 +125905,12 @@ async function pruneClaudeLegacyPluginCache(dryRun, steps) {
|
|
|
125612
125905
|
return;
|
|
125613
125906
|
const removed = [];
|
|
125614
125907
|
for (const pluginName of LEGACY_PLUGIN_NAMES) {
|
|
125615
|
-
const pluginDir =
|
|
125908
|
+
const pluginDir = join147(cacheRoot, MARKETPLACE_NAME, pluginName);
|
|
125616
125909
|
if (!existsSync39(pluginDir))
|
|
125617
125910
|
continue;
|
|
125618
125911
|
removed.push(`${MARKETPLACE_NAME}/${pluginName}`);
|
|
125619
125912
|
if (!dryRun) {
|
|
125620
|
-
await
|
|
125913
|
+
await rm36(pluginDir, { recursive: true, force: true });
|
|
125621
125914
|
}
|
|
125622
125915
|
}
|
|
125623
125916
|
if (removed.length > 0) {
|
|
@@ -125629,12 +125922,12 @@ async function pruneClaudeLegacyPluginCache(dryRun, steps) {
|
|
|
125629
125922
|
}
|
|
125630
125923
|
}
|
|
125631
125924
|
async function pruneClaudeSupersededContextCache(root2, dryRun, steps) {
|
|
125632
|
-
const manifest = await readFile120(
|
|
125925
|
+
const manifest = await readFile120(join147(root2, "claude", ".claude-plugin", "plugin.json"), "utf8").then((content3) => JSON.parse(content3)).catch(() => null);
|
|
125633
125926
|
const currentVersion = typeof manifest?.version === "string" ? manifest.version : null;
|
|
125634
125927
|
if (!currentVersion)
|
|
125635
125928
|
return;
|
|
125636
|
-
const pluginDir =
|
|
125637
|
-
const staleVersions = (await
|
|
125929
|
+
const pluginDir = join147(claudePluginCacheRoot(), MARKETPLACE_NAME, PLUGIN_NAME);
|
|
125930
|
+
const staleVersions = (await readdir37(pluginDir, { withFileTypes: true }).catch(() => [])).filter((entry) => entry.isDirectory() && entry.name !== currentVersion).map((entry) => entry.name);
|
|
125638
125931
|
if (staleVersions.length === 0)
|
|
125639
125932
|
return;
|
|
125640
125933
|
steps.push({
|
|
@@ -125643,7 +125936,7 @@ async function pruneClaudeSupersededContextCache(root2, dryRun, steps) {
|
|
|
125643
125936
|
status: dryRun ? "planned" : "ran"
|
|
125644
125937
|
});
|
|
125645
125938
|
if (!dryRun) {
|
|
125646
|
-
await Promise.all(staleVersions.map((version3) =>
|
|
125939
|
+
await Promise.all(staleVersions.map((version3) => rm36(join147(pluginDir, version3), { recursive: true, force: true })));
|
|
125647
125940
|
}
|
|
125648
125941
|
}
|
|
125649
125942
|
function enableCodexPluginConfig(content3) {
|
|
@@ -125707,7 +126000,7 @@ source = ${JSON.stringify(root2)}
|
|
|
125707
126000
|
`;
|
|
125708
126001
|
}
|
|
125709
126002
|
async function ensureCodexPluginEnabled() {
|
|
125710
|
-
const configPath =
|
|
126003
|
+
const configPath = join147(codexHome(), "config.toml");
|
|
125711
126004
|
await mkdir46(dirname55(configPath), { recursive: true });
|
|
125712
126005
|
const current3 = await readFile120(configPath, "utf8").catch(() => "");
|
|
125713
126006
|
const next2 = enableCodexPluginConfig(current3);
|
|
@@ -125716,7 +126009,7 @@ async function ensureCodexPluginEnabled() {
|
|
|
125716
126009
|
}
|
|
125717
126010
|
}
|
|
125718
126011
|
async function ensureCodexLocalMarketplace(root2) {
|
|
125719
|
-
const configPath =
|
|
126012
|
+
const configPath = join147(codexHome(), "config.toml");
|
|
125720
126013
|
await mkdir46(dirname55(configPath), { recursive: true });
|
|
125721
126014
|
const current3 = await readFile120(configPath, "utf8").catch(() => "");
|
|
125722
126015
|
const next2 = upsertCodexLocalMarketplaceConfig(current3, root2);
|
|
@@ -125725,7 +126018,7 @@ async function ensureCodexLocalMarketplace(root2) {
|
|
|
125725
126018
|
}
|
|
125726
126019
|
}
|
|
125727
126020
|
async function codexPluginVersion(root2) {
|
|
125728
|
-
const manifestPath =
|
|
126021
|
+
const manifestPath = join147(root2, "codex", ".codex-plugin", "plugin.json");
|
|
125729
126022
|
const manifest = JSON.parse(await readFile120(manifestPath, "utf8"));
|
|
125730
126023
|
if (typeof manifest.version !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(manifest.version)) {
|
|
125731
126024
|
throw new Error(`Codex plugin manifest has an invalid version: ${manifestPath}`);
|
|
@@ -125733,13 +126026,13 @@ async function codexPluginVersion(root2) {
|
|
|
125733
126026
|
return manifest.version;
|
|
125734
126027
|
}
|
|
125735
126028
|
function codexPluginCacheDir(version3) {
|
|
125736
|
-
return
|
|
126029
|
+
return join147(codexHome(), "plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME, version3);
|
|
125737
126030
|
}
|
|
125738
126031
|
async function replaceDirectoryFromSource(source2, target) {
|
|
125739
126032
|
await mkdir46(dirname55(target), { recursive: true });
|
|
125740
126033
|
const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
|
|
125741
126034
|
const previous3 = `${target}.previous-${process.pid}-${Date.now()}`;
|
|
125742
|
-
await
|
|
126035
|
+
await rm36(temporary, { recursive: true, force: true });
|
|
125743
126036
|
await cp4(source2, temporary, { recursive: true, force: true });
|
|
125744
126037
|
const hadPrevious = existsSync39(target);
|
|
125745
126038
|
try {
|
|
@@ -125747,16 +126040,16 @@ async function replaceDirectoryFromSource(source2, target) {
|
|
|
125747
126040
|
await rename13(target, previous3);
|
|
125748
126041
|
await rename13(temporary, target);
|
|
125749
126042
|
if (hadPrevious)
|
|
125750
|
-
await
|
|
126043
|
+
await rm36(previous3, { recursive: true, force: true });
|
|
125751
126044
|
} catch (error) {
|
|
125752
|
-
await
|
|
126045
|
+
await rm36(temporary, { recursive: true, force: true });
|
|
125753
126046
|
if (hadPrevious && !existsSync39(target) && existsSync39(previous3))
|
|
125754
126047
|
await rename13(previous3, target);
|
|
125755
126048
|
throw error;
|
|
125756
126049
|
}
|
|
125757
126050
|
}
|
|
125758
126051
|
async function materializeCodexPluginCache(root2, version3, dryRun, steps) {
|
|
125759
|
-
const source2 =
|
|
126052
|
+
const source2 = join147(root2, "codex");
|
|
125760
126053
|
const target = codexPluginCacheDir(version3);
|
|
125761
126054
|
steps.push({
|
|
125762
126055
|
agent: "codex",
|
|
@@ -125768,13 +126061,13 @@ async function materializeCodexPluginCache(root2, version3, dryRun, steps) {
|
|
|
125768
126061
|
await replaceDirectoryFromSource(source2, target);
|
|
125769
126062
|
}
|
|
125770
126063
|
async function bundledProviderSkillNames(root2) {
|
|
125771
|
-
const skillsRoot =
|
|
125772
|
-
const entries2 = await
|
|
126064
|
+
const skillsRoot = join147(root2, "skills");
|
|
126065
|
+
const entries2 = await readdir37(skillsRoot, { withFileTypes: true });
|
|
125773
126066
|
const names = [];
|
|
125774
126067
|
for (const entry of entries2) {
|
|
125775
126068
|
if (!entry.isDirectory() || entry.name === "context")
|
|
125776
126069
|
continue;
|
|
125777
|
-
const skillPath =
|
|
126070
|
+
const skillPath = join147(skillsRoot, entry.name, "SKILL.md");
|
|
125778
126071
|
if (!existsSync39(skillPath))
|
|
125779
126072
|
continue;
|
|
125780
126073
|
const skill = await readFile120(skillPath, "utf8");
|
|
@@ -125789,10 +126082,10 @@ async function bundledProviderSkillNames(root2) {
|
|
|
125789
126082
|
return names;
|
|
125790
126083
|
}
|
|
125791
126084
|
async function materializeProviderSkills(root2, targetRoot, agent, dryRun, steps) {
|
|
125792
|
-
const sourceRoot =
|
|
126085
|
+
const sourceRoot = join147(root2, "skills");
|
|
125793
126086
|
for (const name3 of await bundledProviderSkillNames(root2)) {
|
|
125794
|
-
const source2 =
|
|
125795
|
-
const target =
|
|
126087
|
+
const source2 = join147(sourceRoot, name3);
|
|
126088
|
+
const target = join147(targetRoot, name3);
|
|
125796
126089
|
steps.push({
|
|
125797
126090
|
agent,
|
|
125798
126091
|
command: `materialize lifecycle Provider skill: ${shellQuote8(source2)} -> ${shellQuote8(target)}`,
|
|
@@ -125803,7 +126096,7 @@ async function materializeProviderSkills(root2, targetRoot, agent, dryRun, steps
|
|
|
125803
126096
|
}
|
|
125804
126097
|
}
|
|
125805
126098
|
async function installCursor(root2, dryRun, steps) {
|
|
125806
|
-
const source2 =
|
|
126099
|
+
const source2 = join147(root2, "cursor");
|
|
125807
126100
|
const target = cursorPluginRoot();
|
|
125808
126101
|
steps.push({
|
|
125809
126102
|
agent: "cursor",
|
|
@@ -125858,12 +126151,12 @@ async function installCodex(root2, dryRun, steps) {
|
|
|
125858
126151
|
steps.push({ agent: "codex", command: commandLine("codex", addArgs), status: dryRun ? "planned" : "ran" });
|
|
125859
126152
|
steps.push({
|
|
125860
126153
|
agent: "codex",
|
|
125861
|
-
command: `ensure ${shellQuote8(
|
|
126154
|
+
command: `ensure ${shellQuote8(join147(codexHome(), "config.toml"))} registers local marketplace ${shellQuote8(MARKETPLACE_NAME)}`,
|
|
125862
126155
|
status: dryRun ? "planned" : "ran"
|
|
125863
126156
|
});
|
|
125864
126157
|
steps.push({
|
|
125865
126158
|
agent: "codex",
|
|
125866
|
-
command: `ensure ${shellQuote8(
|
|
126159
|
+
command: `ensure ${shellQuote8(join147(codexHome(), "config.toml"))} enables ${shellQuote8(PLUGIN_ID)}`,
|
|
125867
126160
|
status: dryRun ? "planned" : "ran"
|
|
125868
126161
|
});
|
|
125869
126162
|
if (dryRun) {
|
|
@@ -125918,13 +126211,13 @@ function pluginRootCandidates() {
|
|
|
125918
126211
|
return [resolve54(envRoot)];
|
|
125919
126212
|
const candidates = [];
|
|
125920
126213
|
for (const dir of packageCandidateDirs()) {
|
|
125921
|
-
candidates.push(
|
|
125922
|
-
candidates.push(
|
|
126214
|
+
candidates.push(join148(dir, "plugins"));
|
|
126215
|
+
candidates.push(join148(dir, "dist", "plugins"));
|
|
125923
126216
|
}
|
|
125924
126217
|
return [...new Set(candidates)];
|
|
125925
126218
|
}
|
|
125926
126219
|
function isInstallablePluginRoot(root2) {
|
|
125927
|
-
return existsSync40(
|
|
126220
|
+
return existsSync40(join148(root2, ".claude-plugin", "marketplace.json")) && existsSync40(join148(root2, ".agents", "plugins", "marketplace.json")) && existsSync40(join148(root2, "claude", ".claude-plugin", "plugin.json")) && existsSync40(join148(root2, "codex", ".codex-plugin", "plugin.json")) && existsSync40(join148(root2, "cursor", ".cursor-plugin", "plugin.json")) && existsSync40(join148(root2, "skills"));
|
|
125928
126221
|
}
|
|
125929
126222
|
function resolveBundledPluginsRoot() {
|
|
125930
126223
|
const candidates = pluginRootCandidates();
|
|
@@ -126190,10 +126483,10 @@ function readQuickstartPath() {
|
|
|
126190
126483
|
try {
|
|
126191
126484
|
let dir = dirname57(fileURLToPath12(import.meta.url));
|
|
126192
126485
|
for (let i2 = 0;i2 < 8; i2++) {
|
|
126193
|
-
const candidate =
|
|
126486
|
+
const candidate = join149(dir, "docs", "quickstart.md");
|
|
126194
126487
|
if (existsSync41(candidate))
|
|
126195
126488
|
return candidate;
|
|
126196
|
-
const pkg =
|
|
126489
|
+
const pkg = join149(dir, "package.json");
|
|
126197
126490
|
if (existsSync41(pkg))
|
|
126198
126491
|
return candidate;
|
|
126199
126492
|
const parent2 = dirname57(dir);
|
|
@@ -126202,7 +126495,7 @@ function readQuickstartPath() {
|
|
|
126202
126495
|
dir = parent2;
|
|
126203
126496
|
}
|
|
126204
126497
|
} catch {}
|
|
126205
|
-
return
|
|
126498
|
+
return join149(dirname57(fileURLToPath12(import.meta.url)), "docs", "quickstart.md");
|
|
126206
126499
|
}
|
|
126207
126500
|
var GREEN = "\x1B[32m";
|
|
126208
126501
|
var RESET = "\x1B[0m";
|