@cortexkit/pi-magic-context 0.49.70 → 0.49.71

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.
Files changed (2) hide show
  1. package/dist/index.js +156 -84
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -3608,7 +3608,7 @@ function startHostStallProfilerSwitch() {
3608
3608
  // package.json
3609
3609
  var package_default = {
3610
3610
  name: "@cortexkit/pi-magic-context",
3611
- version: "0.49.70",
3611
+ version: "0.49.71",
3612
3612
  type: "module",
3613
3613
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3614
3614
  main: "dist/index.js",
@@ -11543,7 +11543,7 @@ ${currentDocs?.structure ?? "(read from project)"}
11543
11543
 
11544
11544
  Find claims in these sections that the diff makes wrong or incomplete. Propose one focused change per claim or section. Do not investigate unrelated areas. Read the docs and relevant source with read-only tools. These files are short maps read by every agent in every session. Describe how the system works now, never what changed or when: no change log, dates, or commit lists. One short paragraph per subsystem at most. Mechanism detail belongs in docs/architecture/; you may name a docs page for it but never move that detail into these two files. Propose a change only when code contradicts the docs or a major piece is missing. Prefer rewriting a stale sentence to adding one. Propose nothing when nothing is wrong. Keep both files within the combined budget. Never touch protected regions (<!-- mc:protected START ... --> through <!-- mc:protected END -->); preserve their bytes.
11545
11545
 
11546
- Return ONLY a JSON array (or []), with each entry {"file":"ARCHITECTURE.md"|"STRUCTURE.md","action":"replace"|"add"|"remove","heading":"## Exact section heading","text":"## Full replacement section including heading and body (empty for remove)","reason":"one-line reason"}. A replacement includes the entire section, including its heading. Additions are appended at the end of the file. Do not include any unmodified sections. No file writes.`;
11546
+ Return ONLY a JSON array (or []), with each entry {"file":"ARCHITECTURE.md"|"STRUCTURE.md","action":"replace"|"add"|"remove","heading":"## Exact section heading","text":"## Full section including heading and body (empty for remove)","reason":"one-line reason"}. A section is its heading and everything under it until the next heading of the same or a higher level outside code fences, or the end of the file. Replace, add, or remove exactly one whole section per entry, including its subsections. Additions are appended at the end of the file. Do not include entries for unmodified sections. No file writes.`;
11547
11547
  }
11548
11548
  function buildDreamTaskPrompt(task, args) {
11549
11549
  switch (task) {
@@ -12648,23 +12648,35 @@ ${stat}`
12648
12648
  return null;
12649
12649
  }
12650
12650
  }
12651
- function sections(text) {
12652
- const lines = text.split(`
12653
- `);
12651
+ var ATX_HEADING = /^ {0,3}(#{1,6})(?=[ \t]|$)/;
12652
+ function sections(lines) {
12654
12653
  const result = [];
12655
- let fenced = false;
12654
+ const open = [];
12655
+ let fence;
12656
12656
  for (let i = 0;i < lines.length; i++) {
12657
- if (/^\s*(```|~~~)/.test(lines[i]))
12658
- fenced = !fenced;
12659
- if (!fenced && /^#{1,6} \S/.test(lines[i])) {
12660
- if (result.length)
12661
- result[result.length - 1].end = i;
12662
- result.push({ heading: lines[i], text: "", start: i, end: lines.length });
12657
+ const heading = lines[i].replace(/\r$/, "");
12658
+ const marker = heading.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
12659
+ if (fence) {
12660
+ if (marker?.[1].startsWith(fence) && !marker[2].trim())
12661
+ fence = undefined;
12662
+ continue;
12663
+ }
12664
+ if (marker && (marker[1][0] === "~" || !marker[2].includes("`"))) {
12665
+ fence = marker[1];
12666
+ continue;
12667
+ }
12668
+ const match = heading.match(ATX_HEADING);
12669
+ if (!match)
12670
+ continue;
12671
+ const level = match[1].length;
12672
+ for (let previous = open.at(-1);previous && previous.level >= level; previous = open.at(-1)) {
12673
+ previous.end = i;
12674
+ open.pop();
12663
12675
  }
12676
+ const section = { heading, level, start: i, end: lines.length };
12677
+ result.push(section);
12678
+ open.push(section);
12664
12679
  }
12665
- for (const section of result)
12666
- section.text = lines.slice(section.start, section.end).join(`
12667
- `);
12668
12680
  return result;
12669
12681
  }
12670
12682
  function protectedBytes(text) {
@@ -12687,76 +12699,142 @@ function diff(name, before, after) {
12687
12699
  }
12688
12700
  }
12689
12701
  function parseDocsProposalOutput(output) {
12690
- const match = output.match(/```json\s*([\s\S]*?)```/);
12691
- const parsed = JSON.parse(match?.[1] ?? output);
12702
+ let parsed;
12703
+ try {
12704
+ parsed = JSON.parse(output);
12705
+ } catch (error) {
12706
+ const match = output.match(/```json[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```(?=\s|$)/) ?? output.match(/```json\s*([\s\S]*?)```/);
12707
+ if (!match)
12708
+ throw error;
12709
+ parsed = JSON.parse(match[1]);
12710
+ }
12692
12711
  if (!Array.isArray(parsed))
12693
12712
  throw new Error("proposal must be a JSON array");
12694
- const changes = parsed;
12695
- if (changes.some((item) => !item || !FILES.includes(item.file)))
12696
- throw new Error("unknown proposal file");
12713
+ return parsed;
12714
+ }
12715
+ function readChange(item) {
12716
+ if (!item || typeof item !== "object" || Array.isArray(item))
12717
+ return "expected an object";
12718
+ const { file, action, heading, text, reason } = item;
12719
+ if (file !== "ARCHITECTURE.md" && file !== "STRUCTURE.md")
12720
+ return "unknown proposal file";
12721
+ if (action !== "replace" && action !== "add" && action !== "remove")
12722
+ return "invalid action";
12723
+ if (typeof heading !== "string" || /[\r\n]/.test(heading) || !ATX_HEADING.test(heading))
12724
+ return "invalid section heading";
12725
+ if (typeof text !== "string")
12726
+ return "section text must be a string";
12727
+ if (typeof reason !== "string" || !reason.trim() || /[\r\n]/.test(reason))
12728
+ return "expected a one-line reason";
12729
+ return { file, action, heading, text, reason };
12730
+ }
12731
+ function applyChange(before, change) {
12732
+ const lines = before.split(`
12733
+ `);
12734
+ const existing = sections(lines);
12735
+ const index = existing.findIndex((item) => item.heading === change.heading);
12736
+ const replacement = change.action === "remove" ? [] : change.text.trimEnd().split(`
12737
+ `);
12738
+ const inserted = sections(replacement);
12739
+ const wholeSection = inserted[0]?.heading === change.heading && inserted[0].start === 0 && inserted[0].end === replacement.length;
12740
+ const expectedHeadings = existing.map((item) => item.heading);
12741
+ const insertedHeadings = inserted.map((item) => item.heading);
12742
+ let after;
12743
+ if (change.action === "add") {
12744
+ if (index !== -1 || !wholeSection)
12745
+ return `invalid addition ${change.heading}`;
12746
+ after = `${before.endsWith(`
12747
+ `) ? before : `${before}
12748
+ `}
12749
+ ${replacement.join(`
12750
+ `)}
12751
+ `;
12752
+ expectedHeadings.push(...insertedHeadings);
12753
+ } else {
12754
+ if (index === -1)
12755
+ return `missing section ${change.heading}`;
12756
+ if (change.action === "replace" && !wholeSection)
12757
+ return `invalid replacement ${change.heading}`;
12758
+ const section = existing[index];
12759
+ const affected = existing.filter((item) => item.start >= section.start && item.start < section.end);
12760
+ expectedHeadings.splice(index, affected.length, ...insertedHeadings);
12761
+ if (change.action === "replace" && section.end === lines.length && before.endsWith(`
12762
+ `))
12763
+ replacement.push("");
12764
+ lines.splice(section.start, section.end - section.start, ...replacement);
12765
+ after = lines.join(`
12766
+ `);
12767
+ }
12768
+ if (JSON.stringify(protectedBytes(before)) !== JSON.stringify(protectedBytes(after)))
12769
+ return `protected region changed in ${change.file}`;
12770
+ if (JSON.stringify(sections(after.split(`
12771
+ `)).map((item) => item.heading)) !== JSON.stringify(expectedHeadings))
12772
+ return `markdown structure changed in ${change.file}`;
12773
+ if (after === before)
12774
+ return "no doc changes proposed";
12775
+ return { after };
12776
+ }
12777
+ function applyChanges(items, originals, overBudget) {
12778
+ const docs = { ...originals };
12779
+ const kept = [];
12780
+ const dropped = [];
12697
12781
  const seen = new Set;
12698
- for (const change of changes) {
12782
+ for (const [index, item] of items.entries()) {
12783
+ const change = overBudget.get(index) ?? readChange(item);
12784
+ if (typeof change === "string") {
12785
+ dropped.push({ index, reason: change });
12786
+ continue;
12787
+ }
12699
12788
  const key = `${change.file}:${change.heading}`;
12700
- if (!["replace", "add", "remove"].includes(change.action) || typeof change.heading !== "string" || !/^#{1,6} [^\r\n]+$/.test(change.heading) || typeof change.text !== "string" || typeof change.reason !== "string" || !change.reason.trim() || /[\r\n]/.test(change.reason) || seen.has(key))
12701
- throw new Error(`invalid section change in ${change.file}`);
12789
+ const before = docs[change.file];
12790
+ const result = seen.has(key) ? `duplicate section change ${change.heading}` : applyChange(before, change);
12791
+ if (typeof result === "string") {
12792
+ dropped.push({ index, reason: result });
12793
+ continue;
12794
+ }
12795
+ kept.push({ index, change, grew: result.after.length > before.length });
12796
+ docs[change.file] = result.after;
12702
12797
  seen.add(key);
12703
12798
  }
12704
- return changes;
12799
+ const tokens = FILES.reduce((sum, file) => sum + Math.ceil(docs[file].length / 3.5), 0);
12800
+ return { docs, kept, dropped, tokens };
12705
12801
  }
12706
12802
  function validateDocsProposal(projectDir, output, budget, expected) {
12707
- if (Object.entries(expected).some(([name, value]) => docsBaseHashes(projectDir)[name] !== value))
12803
+ const readDoc = (file) => {
12804
+ const path = join8(projectDir, file);
12805
+ return existsSync6(path) ? readFileSync6(path, "utf8") : "";
12806
+ };
12807
+ const originals = {
12808
+ "ARCHITECTURE.md": readDoc("ARCHITECTURE.md"),
12809
+ "STRUCTURE.md": readDoc("STRUCTURE.md")
12810
+ };
12811
+ if (Object.keys(expected).some((name) => !FILES.some((file) => file === name && hash(originals[file]) === expected[name])))
12708
12812
  throw new Error("base drifted");
12709
- const changes = parseDocsProposalOutput(output);
12710
- if (!changes.length)
12711
- throw new Error("empty proposal");
12712
- let tokens = 0;
12713
- let diffs = "";
12714
- for (const file of FILES) {
12715
- const before = existsSync6(join8(projectDir, file)) ? readFileSync6(join8(projectDir, file), "utf8") : "";
12716
- let after = before;
12717
- for (const change of changes.filter((item) => item.file === file)) {
12718
- const section = sections(after).find((item) => item.heading === change.heading);
12719
- if (change.action === "add") {
12720
- if (section || !change.text.startsWith(`${change.heading}
12721
- `))
12722
- throw new Error(`invalid addition ${change.heading}`);
12723
- after += `${after.endsWith(`
12724
- `) ? "" : `
12725
- `}
12726
- ${change.text.trimEnd()}
12727
- `;
12728
- } else {
12729
- if (!section)
12730
- throw new Error(`missing section ${change.heading}`);
12731
- if (change.action === "replace" && (!change.text.startsWith(`${change.heading}
12732
- `) || sections(change.text).length !== 1))
12733
- throw new Error(`invalid replacement ${change.heading}`);
12734
- const lines = after.split(`
12735
- `);
12736
- lines.splice(section.start, section.end - section.start, ...change.action === "remove" ? [] : change.text.trimEnd().split(`
12737
- `));
12738
- after = lines.join(`
12739
- `);
12740
- }
12741
- }
12742
- if (JSON.stringify(protectedBytes(before)) !== JSON.stringify(protectedBytes(after)))
12743
- throw new Error(`protected region changed in ${file}`);
12744
- const originalHeadings = sections(before).map((item) => item.heading);
12745
- const expectedHeadings = originalHeadings.filter((heading) => !changes.some((item) => item.file === file && item.action === "remove" && item.heading === heading)).concat(changes.filter((item) => item.file === file && item.action === "add").map((item) => item.heading));
12746
- if (JSON.stringify(sections(after).map((item) => item.heading)) !== JSON.stringify(expectedHeadings))
12747
- throw new Error(`markdown structure changed in ${file}`);
12748
- tokens += Math.ceil(after.length / 3.5);
12749
- if (after !== before)
12750
- diffs += diff(file, before, after);
12813
+ const items = parseDocsProposalOutput(output);
12814
+ const overBudget = new Map;
12815
+ let result = applyChanges(items, originals, overBudget);
12816
+ while (result.tokens > budget && result.kept.length) {
12817
+ const reason = `over budget: ${result.tokens} > ${budget}`;
12818
+ const latestGrowth = [...result.kept].reverse().find((item) => item.grew);
12819
+ if (latestGrowth)
12820
+ overBudget.set(latestGrowth.index, reason);
12821
+ else
12822
+ for (const item of result.kept)
12823
+ overBudget.set(item.index, reason);
12824
+ result = applyChanges(items, originals, overBudget);
12751
12825
  }
12752
- if (tokens > budget)
12753
- throw new Error(`over budget: ${tokens} > ${budget}`);
12754
- if (!diffs)
12755
- throw new Error("no doc changes proposed");
12756
- return { changes, tokens, diffs };
12826
+ const diffs = FILES.filter((file) => originals[file] !== result.docs[file]).map((file) => diff(file, originals[file], result.docs[file])).join("");
12827
+ return {
12828
+ changes: result.kept.map((item) => item.change),
12829
+ dropped: result.dropped,
12830
+ tokens: result.tokens,
12831
+ diffs
12832
+ };
12757
12833
  }
12758
12834
  function writeDocsProposal(projectDir, output, budget, expected, head) {
12759
12835
  const result = validateDocsProposal(projectDir, output, budget, expected);
12836
+ if (!result.diffs)
12837
+ return { path: null, dropped: result.dropped };
12760
12838
  const dir = proposalDir(projectDir);
12761
12839
  mkdirSync2(join8(dir, "superseded"), { recursive: true });
12762
12840
  ensureCortexKitArtifactGitignore(projectDir);
@@ -12790,7 +12868,7 @@ ${result.diffs}
12790
12868
  for (const old of listPendingDocsProposals(projectDir))
12791
12869
  if (old !== path)
12792
12870
  renameSync(old, join8(dir, "superseded", old.split("/").at(-1) ?? "proposal.md"));
12793
- return path;
12871
+ return { path, dropped: result.dropped };
12794
12872
  }
12795
12873
 
12796
12874
  // ../plugin/src/agents/smart-note-compiler.ts
@@ -19399,19 +19477,13 @@ async function runAgenticTask(config, ctx, helpers) {
19399
19477
  recordInvocation("completed", run.output);
19400
19478
  if (task === "maintain-docs" && docsHashes && changes) {
19401
19479
  try {
19402
- if (parseDocsProposalOutput(String(run.validated)).length === 0) {
19403
- helpers.recordRun("completed", null, { progress: "no corrections proposed" });
19404
- return {
19405
- status: "completed",
19406
- detail: "no corrections proposed",
19407
- schedulePatch: { taskStateJson: JSON.stringify({ head: changes.head }) }
19408
- };
19409
- }
19410
- const path = writeDocsProposal(docsDir, String(run.validated), config.docsMaxTokens ?? 12000, docsHashes, changes.head);
19411
- helpers.recordRun("completed", null, { progress: `proposal: ${path}` });
19480
+ const { path, dropped } = writeDocsProposal(docsDir, String(run.validated), config.docsMaxTokens ?? 12000, docsHashes, changes.head);
19481
+ const outcome = path ? `proposal: ${path}` : "no corrections proposed";
19482
+ const detail = dropped.length ? `${outcome}; dropped ${dropped.map(({ index, reason }) => `entry ${index + 1}: ${reason}`).join("; ")}` : outcome;
19483
+ helpers.recordRun("completed", null, { progress: detail });
19412
19484
  return {
19413
19485
  status: "completed",
19414
- detail: `proposal: ${path}`,
19486
+ detail,
19415
19487
  schedulePatch: { taskStateJson: JSON.stringify({ head: changes.head }) }
19416
19488
  };
19417
19489
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.49.70",
3
+ "version": "0.49.71",
4
4
  "type": "module",
5
5
  "description": "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",