@cortexkit/pi-magic-context 0.49.69 → 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.
@@ -7,7 +7,7 @@ import {
7
7
  ceilProviderOutputTokens2,
8
8
  withoutProviderTemperature2,
9
9
  historianCalibrationExtension
10
- } from "./index-0b5kqg7n.js";
10
+ } from "./index-j4mwdz3q.js";
11
11
  import"./index-4knyh1kt.js";
12
12
  import"./index-6x556c2q.js";
13
13
  import"./index-tm11k42a.js";
@@ -412,6 +412,7 @@ plan:
412
412
  enabled: false
413
413
  defaultOnStartup: false
414
414
  `;
415
+ var OMP_CHILD_TOOL_ENV = { PI_AUTO_QA: "0" };
415
416
  function registerSubagentToolBoundary(pi) {
416
417
  pi.registerFlag(SUBAGENT_TOOL_ALLOWLIST_FLAG, {
417
418
  description: "Exact active tool names for a Magic Context hidden child.",
@@ -613,4 +614,4 @@ function historianCalibrationExtension(pi) {
613
614
  });
614
615
  }
615
616
 
616
- export { DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS, buildHiddenAgentRegistrations, logTemperatureDecision, readHostSystemPrompt, subagentStepCap, SubagentTelemetry, OMP_CHILD_TOOL_CONFIG, HISTORIAN_TEMPERATURE_ENV2, HISTORIAN_CACHE_TAIL_ENV2, HISTORIAN_MAX_OUTPUT_TOKENS_ENV2, SUBAGENT_OUTPUT_CEILING_ENV2, calibrateHistorianProviderPayload2, ceilProviderOutputTokens2, withoutProviderTemperature2, historianCalibrationExtension };
617
+ export { DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS, buildHiddenAgentRegistrations, logTemperatureDecision, readHostSystemPrompt, subagentStepCap, SubagentTelemetry, OMP_CHILD_TOOL_CONFIG, OMP_CHILD_TOOL_ENV, HISTORIAN_TEMPERATURE_ENV2, HISTORIAN_CACHE_TAIL_ENV2, HISTORIAN_MAX_OUTPUT_TOKENS_ENV2, SUBAGENT_OUTPUT_CEILING_ENV2, calibrateHistorianProviderPayload2, ceilProviderOutputTokens2, withoutProviderTemperature2, historianCalibrationExtension };
package/dist/index.js CHANGED
@@ -832,10 +832,11 @@ import {
832
832
  subagentStepCap,
833
833
  SubagentTelemetry,
834
834
  OMP_CHILD_TOOL_CONFIG,
835
+ OMP_CHILD_TOOL_ENV,
835
836
  HISTORIAN_CACHE_TAIL_ENV2,
836
837
  HISTORIAN_MAX_OUTPUT_TOKENS_ENV2,
837
838
  SUBAGENT_OUTPUT_CEILING_ENV2
838
- } from "./index-0b5kqg7n.js";
839
+ } from "./index-j4mwdz3q.js";
839
840
  import {
840
841
  PI_CONTEXT_BUDGET,
841
842
  PiContextDeadlineError,
@@ -3607,7 +3608,7 @@ function startHostStallProfilerSwitch() {
3607
3608
  // package.json
3608
3609
  var package_default = {
3609
3610
  name: "@cortexkit/pi-magic-context",
3610
- version: "0.49.69",
3611
+ version: "0.49.71",
3611
3612
  type: "module",
3612
3613
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3613
3614
  main: "dist/index.js",
@@ -11542,7 +11543,7 @@ ${currentDocs?.structure ?? "(read from project)"}
11542
11543
 
11543
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.
11544
11545
 
11545
- 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.`;
11546
11547
  }
11547
11548
  function buildDreamTaskPrompt(task, args) {
11548
11549
  switch (task) {
@@ -12647,23 +12648,35 @@ ${stat}`
12647
12648
  return null;
12648
12649
  }
12649
12650
  }
12650
- function sections(text) {
12651
- const lines = text.split(`
12652
- `);
12651
+ var ATX_HEADING = /^ {0,3}(#{1,6})(?=[ \t]|$)/;
12652
+ function sections(lines) {
12653
12653
  const result = [];
12654
- let fenced = false;
12654
+ const open = [];
12655
+ let fence;
12655
12656
  for (let i = 0;i < lines.length; i++) {
12656
- if (/^\s*(```|~~~)/.test(lines[i]))
12657
- fenced = !fenced;
12658
- if (!fenced && /^#{1,6} \S/.test(lines[i])) {
12659
- if (result.length)
12660
- result[result.length - 1].end = i;
12661
- 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();
12662
12675
  }
12676
+ const section = { heading, level, start: i, end: lines.length };
12677
+ result.push(section);
12678
+ open.push(section);
12663
12679
  }
12664
- for (const section of result)
12665
- section.text = lines.slice(section.start, section.end).join(`
12666
- `);
12667
12680
  return result;
12668
12681
  }
12669
12682
  function protectedBytes(text) {
@@ -12686,76 +12699,142 @@ function diff(name, before, after) {
12686
12699
  }
12687
12700
  }
12688
12701
  function parseDocsProposalOutput(output) {
12689
- const match = output.match(/```json\s*([\s\S]*?)```/);
12690
- 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
+ }
12691
12711
  if (!Array.isArray(parsed))
12692
12712
  throw new Error("proposal must be a JSON array");
12693
- const changes = parsed;
12694
- if (changes.some((item) => !item || !FILES.includes(item.file)))
12695
- 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 = [];
12696
12781
  const seen = new Set;
12697
- 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
+ }
12698
12788
  const key = `${change.file}:${change.heading}`;
12699
- 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))
12700
- 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;
12701
12797
  seen.add(key);
12702
12798
  }
12703
- return changes;
12799
+ const tokens = FILES.reduce((sum, file) => sum + Math.ceil(docs[file].length / 3.5), 0);
12800
+ return { docs, kept, dropped, tokens };
12704
12801
  }
12705
12802
  function validateDocsProposal(projectDir, output, budget, expected) {
12706
- 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])))
12707
12812
  throw new Error("base drifted");
12708
- const changes = parseDocsProposalOutput(output);
12709
- if (!changes.length)
12710
- throw new Error("empty proposal");
12711
- let tokens = 0;
12712
- let diffs = "";
12713
- for (const file of FILES) {
12714
- const before = existsSync6(join8(projectDir, file)) ? readFileSync6(join8(projectDir, file), "utf8") : "";
12715
- let after = before;
12716
- for (const change of changes.filter((item) => item.file === file)) {
12717
- const section = sections(after).find((item) => item.heading === change.heading);
12718
- if (change.action === "add") {
12719
- if (section || !change.text.startsWith(`${change.heading}
12720
- `))
12721
- throw new Error(`invalid addition ${change.heading}`);
12722
- after += `${after.endsWith(`
12723
- `) ? "" : `
12724
- `}
12725
- ${change.text.trimEnd()}
12726
- `;
12727
- } else {
12728
- if (!section)
12729
- throw new Error(`missing section ${change.heading}`);
12730
- if (change.action === "replace" && (!change.text.startsWith(`${change.heading}
12731
- `) || sections(change.text).length !== 1))
12732
- throw new Error(`invalid replacement ${change.heading}`);
12733
- const lines = after.split(`
12734
- `);
12735
- lines.splice(section.start, section.end - section.start, ...change.action === "remove" ? [] : change.text.trimEnd().split(`
12736
- `));
12737
- after = lines.join(`
12738
- `);
12739
- }
12740
- }
12741
- if (JSON.stringify(protectedBytes(before)) !== JSON.stringify(protectedBytes(after)))
12742
- throw new Error(`protected region changed in ${file}`);
12743
- const originalHeadings = sections(before).map((item) => item.heading);
12744
- 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));
12745
- if (JSON.stringify(sections(after).map((item) => item.heading)) !== JSON.stringify(expectedHeadings))
12746
- throw new Error(`markdown structure changed in ${file}`);
12747
- tokens += Math.ceil(after.length / 3.5);
12748
- if (after !== before)
12749
- 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);
12750
12825
  }
12751
- if (tokens > budget)
12752
- throw new Error(`over budget: ${tokens} > ${budget}`);
12753
- if (!diffs)
12754
- throw new Error("no doc changes proposed");
12755
- 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
+ };
12756
12833
  }
12757
12834
  function writeDocsProposal(projectDir, output, budget, expected, head) {
12758
12835
  const result = validateDocsProposal(projectDir, output, budget, expected);
12836
+ if (!result.diffs)
12837
+ return { path: null, dropped: result.dropped };
12759
12838
  const dir = proposalDir(projectDir);
12760
12839
  mkdirSync2(join8(dir, "superseded"), { recursive: true });
12761
12840
  ensureCortexKitArtifactGitignore(projectDir);
@@ -12789,7 +12868,7 @@ ${result.diffs}
12789
12868
  for (const old of listPendingDocsProposals(projectDir))
12790
12869
  if (old !== path)
12791
12870
  renameSync(old, join8(dir, "superseded", old.split("/").at(-1) ?? "proposal.md"));
12792
- return path;
12871
+ return { path, dropped: result.dropped };
12793
12872
  }
12794
12873
 
12795
12874
  // ../plugin/src/agents/smart-note-compiler.ts
@@ -19398,19 +19477,13 @@ async function runAgenticTask(config, ctx, helpers) {
19398
19477
  recordInvocation("completed", run.output);
19399
19478
  if (task === "maintain-docs" && docsHashes && changes) {
19400
19479
  try {
19401
- if (parseDocsProposalOutput(String(run.validated)).length === 0) {
19402
- helpers.recordRun("completed", null, { progress: "no corrections proposed" });
19403
- return {
19404
- status: "completed",
19405
- detail: "no corrections proposed",
19406
- schedulePatch: { taskStateJson: JSON.stringify({ head: changes.head }) }
19407
- };
19408
- }
19409
- const path = writeDocsProposal(docsDir, String(run.validated), config.docsMaxTokens ?? 12000, docsHashes, changes.head);
19410
- 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 });
19411
19484
  return {
19412
19485
  status: "completed",
19413
- detail: `proposal: ${path}`,
19486
+ detail,
19414
19487
  schedulePatch: { taskStateJson: JSON.stringify({ head: changes.head }) }
19415
19488
  };
19416
19489
  } catch (error) {
@@ -21432,6 +21505,7 @@ class PiSubagentRunner {
21432
21505
  cwd: options.cwd,
21433
21506
  env: {
21434
21507
  ...parentEnv,
21508
+ ...this.invocation.targetHarness === "omp" ? OMP_CHILD_TOOL_ENV : {},
21435
21509
  [MAGIC_CONTEXT_PI_SUBAGENT_ENV]: "1",
21436
21510
  MAGIC_CONTEXT_SUBAGENT_PROMPT_FILE: systemPromptPath,
21437
21511
  [HISTORIAN_CACHE_TAIL_ENV2]: /^(magic-context-)?historian(?:-recomp)?$/.test(options.agent) && options.accountingSubagent !== "historian_editor" ? options.cacheTail : undefined,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.49.69",
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",