@cortexkit/opencode-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.
@@ -130,7 +130,7 @@ import {
130
130
  applyJsonSchemaParameterDescriptions,
131
131
  MagicContextRpcServer,
132
132
  subagentTemperature
133
- } from "./index-95475ngp.js";
133
+ } from "./index-33bfewqe.js";
134
134
  import {
135
135
  resolveHistorianModel2
136
136
  } from "./index-5kym00ag.js";
@@ -15,12 +15,20 @@ export interface DocsSectionChange {
15
15
  text: string;
16
16
  reason: string;
17
17
  }
18
- export declare function parseDocsProposalOutput(output: string): DocsSectionChange[];
18
+ export declare function parseDocsProposalOutput(output: string): unknown[];
19
+ interface DroppedDocsChange {
20
+ index: number;
21
+ reason: string;
22
+ }
19
23
  export declare function validateDocsProposal(projectDir: string, output: string, budget: number, expected: Record<string, string>): {
20
24
  changes: DocsSectionChange[];
25
+ dropped: DroppedDocsChange[];
21
26
  tokens: number;
22
27
  diffs: string;
23
28
  };
24
- export declare function writeDocsProposal(projectDir: string, output: string, budget: number, expected: Record<string, string>, head: string): string;
29
+ export declare function writeDocsProposal(projectDir: string, output: string, budget: number, expected: Record<string, string>, head: string): {
30
+ path: string | null;
31
+ dropped: DroppedDocsChange[];
32
+ };
25
33
  export {};
26
34
  //# sourceMappingURL=docs-proposals.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"docs-proposals.d.ts","sourceRoot":"","sources":["../../../../src/features/magic-context/dreamer/docs-proposals.ts"],"names":[],"mappings":"AAiBA,QAAA,MAAM,KAAK,8CAA+C,CAAC;AAK3D,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAWzE;AAED,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,EAAE,CAQrE;AAED,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAOl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EAChC,IAAI,EAAE,MAAM,GACb;IAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,OAAO,EAAE,iBAAiB,EAAE,CAAA;CAAE,CAcvD"}
@@ -1120,7 +1120,7 @@ ${currentDocs?.structure ?? "(read from project)"}
1120
1120
 
1121
1121
  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.
1122
1122
 
1123
- 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.`;
1123
+ 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.`;
1124
1124
  }
1125
1125
  function buildDreamTaskPrompt(task, args) {
1126
1126
  switch (task) {
@@ -4302,23 +4302,35 @@ ${stat}`
4302
4302
  return null;
4303
4303
  }
4304
4304
  }
4305
- function sections(text) {
4306
- const lines = text.split(`
4307
- `);
4305
+ var ATX_HEADING = /^ {0,3}(#{1,6})(?=[ \t]|$)/;
4306
+ function sections(lines) {
4308
4307
  const result = [];
4309
- let fenced = false;
4308
+ const open = [];
4309
+ let fence;
4310
4310
  for (let i = 0;i < lines.length; i++) {
4311
- if (/^\s*(```|~~~)/.test(lines[i]))
4312
- fenced = !fenced;
4313
- if (!fenced && /^#{1,6} \S/.test(lines[i])) {
4314
- if (result.length)
4315
- result[result.length - 1].end = i;
4316
- result.push({ heading: lines[i], text: "", start: i, end: lines.length });
4311
+ const heading = lines[i].replace(/\r$/, "");
4312
+ const marker = heading.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
4313
+ if (fence) {
4314
+ if (marker?.[1].startsWith(fence) && !marker[2].trim())
4315
+ fence = undefined;
4316
+ continue;
4317
+ }
4318
+ if (marker && (marker[1][0] === "~" || !marker[2].includes("`"))) {
4319
+ fence = marker[1];
4320
+ continue;
4321
+ }
4322
+ const match = heading.match(ATX_HEADING);
4323
+ if (!match)
4324
+ continue;
4325
+ const level = match[1].length;
4326
+ for (let previous = open.at(-1);previous && previous.level >= level; previous = open.at(-1)) {
4327
+ previous.end = i;
4328
+ open.pop();
4317
4329
  }
4330
+ const section = { heading, level, start: i, end: lines.length };
4331
+ result.push(section);
4332
+ open.push(section);
4318
4333
  }
4319
- for (const section of result)
4320
- section.text = lines.slice(section.start, section.end).join(`
4321
- `);
4322
4334
  return result;
4323
4335
  }
4324
4336
  function protectedBytes(text) {
@@ -4341,76 +4353,142 @@ function diff(name, before, after) {
4341
4353
  }
4342
4354
  }
4343
4355
  function parseDocsProposalOutput(output) {
4344
- const match = output.match(/```json\s*([\s\S]*?)```/);
4345
- const parsed = JSON.parse(match?.[1] ?? output);
4356
+ let parsed;
4357
+ try {
4358
+ parsed = JSON.parse(output);
4359
+ } catch (error) {
4360
+ const match = output.match(/```json[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```(?=\s|$)/) ?? output.match(/```json\s*([\s\S]*?)```/);
4361
+ if (!match)
4362
+ throw error;
4363
+ parsed = JSON.parse(match[1]);
4364
+ }
4346
4365
  if (!Array.isArray(parsed))
4347
4366
  throw new Error("proposal must be a JSON array");
4348
- const changes = parsed;
4349
- if (changes.some((item) => !item || !FILES.includes(item.file)))
4350
- throw new Error("unknown proposal file");
4367
+ return parsed;
4368
+ }
4369
+ function readChange(item) {
4370
+ if (!item || typeof item !== "object" || Array.isArray(item))
4371
+ return "expected an object";
4372
+ const { file, action, heading, text, reason } = item;
4373
+ if (file !== "ARCHITECTURE.md" && file !== "STRUCTURE.md")
4374
+ return "unknown proposal file";
4375
+ if (action !== "replace" && action !== "add" && action !== "remove")
4376
+ return "invalid action";
4377
+ if (typeof heading !== "string" || /[\r\n]/.test(heading) || !ATX_HEADING.test(heading))
4378
+ return "invalid section heading";
4379
+ if (typeof text !== "string")
4380
+ return "section text must be a string";
4381
+ if (typeof reason !== "string" || !reason.trim() || /[\r\n]/.test(reason))
4382
+ return "expected a one-line reason";
4383
+ return { file, action, heading, text, reason };
4384
+ }
4385
+ function applyChange(before, change) {
4386
+ const lines = before.split(`
4387
+ `);
4388
+ const existing = sections(lines);
4389
+ const index = existing.findIndex((item) => item.heading === change.heading);
4390
+ const replacement = change.action === "remove" ? [] : change.text.trimEnd().split(`
4391
+ `);
4392
+ const inserted = sections(replacement);
4393
+ const wholeSection = inserted[0]?.heading === change.heading && inserted[0].start === 0 && inserted[0].end === replacement.length;
4394
+ const expectedHeadings = existing.map((item) => item.heading);
4395
+ const insertedHeadings = inserted.map((item) => item.heading);
4396
+ let after;
4397
+ if (change.action === "add") {
4398
+ if (index !== -1 || !wholeSection)
4399
+ return `invalid addition ${change.heading}`;
4400
+ after = `${before.endsWith(`
4401
+ `) ? before : `${before}
4402
+ `}
4403
+ ${replacement.join(`
4404
+ `)}
4405
+ `;
4406
+ expectedHeadings.push(...insertedHeadings);
4407
+ } else {
4408
+ if (index === -1)
4409
+ return `missing section ${change.heading}`;
4410
+ if (change.action === "replace" && !wholeSection)
4411
+ return `invalid replacement ${change.heading}`;
4412
+ const section = existing[index];
4413
+ const affected = existing.filter((item) => item.start >= section.start && item.start < section.end);
4414
+ expectedHeadings.splice(index, affected.length, ...insertedHeadings);
4415
+ if (change.action === "replace" && section.end === lines.length && before.endsWith(`
4416
+ `))
4417
+ replacement.push("");
4418
+ lines.splice(section.start, section.end - section.start, ...replacement);
4419
+ after = lines.join(`
4420
+ `);
4421
+ }
4422
+ if (JSON.stringify(protectedBytes(before)) !== JSON.stringify(protectedBytes(after)))
4423
+ return `protected region changed in ${change.file}`;
4424
+ if (JSON.stringify(sections(after.split(`
4425
+ `)).map((item) => item.heading)) !== JSON.stringify(expectedHeadings))
4426
+ return `markdown structure changed in ${change.file}`;
4427
+ if (after === before)
4428
+ return "no doc changes proposed";
4429
+ return { after };
4430
+ }
4431
+ function applyChanges(items, originals, overBudget) {
4432
+ const docs = { ...originals };
4433
+ const kept = [];
4434
+ const dropped = [];
4351
4435
  const seen = new Set;
4352
- for (const change of changes) {
4436
+ for (const [index, item] of items.entries()) {
4437
+ const change = overBudget.get(index) ?? readChange(item);
4438
+ if (typeof change === "string") {
4439
+ dropped.push({ index, reason: change });
4440
+ continue;
4441
+ }
4353
4442
  const key = `${change.file}:${change.heading}`;
4354
- 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))
4355
- throw new Error(`invalid section change in ${change.file}`);
4443
+ const before = docs[change.file];
4444
+ const result = seen.has(key) ? `duplicate section change ${change.heading}` : applyChange(before, change);
4445
+ if (typeof result === "string") {
4446
+ dropped.push({ index, reason: result });
4447
+ continue;
4448
+ }
4449
+ kept.push({ index, change, grew: result.after.length > before.length });
4450
+ docs[change.file] = result.after;
4356
4451
  seen.add(key);
4357
4452
  }
4358
- return changes;
4453
+ const tokens = FILES.reduce((sum, file) => sum + Math.ceil(docs[file].length / 3.5), 0);
4454
+ return { docs, kept, dropped, tokens };
4359
4455
  }
4360
4456
  function validateDocsProposal(projectDir, output, budget, expected) {
4361
- if (Object.entries(expected).some(([name, value]) => docsBaseHashes(projectDir)[name] !== value))
4457
+ const readDoc = (file) => {
4458
+ const path = join(projectDir, file);
4459
+ return existsSync2(path) ? readFileSync(path, "utf8") : "";
4460
+ };
4461
+ const originals = {
4462
+ "ARCHITECTURE.md": readDoc("ARCHITECTURE.md"),
4463
+ "STRUCTURE.md": readDoc("STRUCTURE.md")
4464
+ };
4465
+ if (Object.keys(expected).some((name) => !FILES.some((file) => file === name && hash(originals[file]) === expected[name])))
4362
4466
  throw new Error("base drifted");
4363
- const changes = parseDocsProposalOutput(output);
4364
- if (!changes.length)
4365
- throw new Error("empty proposal");
4366
- let tokens = 0;
4367
- let diffs = "";
4368
- for (const file of FILES) {
4369
- const before = existsSync2(join(projectDir, file)) ? readFileSync(join(projectDir, file), "utf8") : "";
4370
- let after = before;
4371
- for (const change of changes.filter((item) => item.file === file)) {
4372
- const section = sections(after).find((item) => item.heading === change.heading);
4373
- if (change.action === "add") {
4374
- if (section || !change.text.startsWith(`${change.heading}
4375
- `))
4376
- throw new Error(`invalid addition ${change.heading}`);
4377
- after += `${after.endsWith(`
4378
- `) ? "" : `
4379
- `}
4380
- ${change.text.trimEnd()}
4381
- `;
4382
- } else {
4383
- if (!section)
4384
- throw new Error(`missing section ${change.heading}`);
4385
- if (change.action === "replace" && (!change.text.startsWith(`${change.heading}
4386
- `) || sections(change.text).length !== 1))
4387
- throw new Error(`invalid replacement ${change.heading}`);
4388
- const lines = after.split(`
4389
- `);
4390
- lines.splice(section.start, section.end - section.start, ...change.action === "remove" ? [] : change.text.trimEnd().split(`
4391
- `));
4392
- after = lines.join(`
4393
- `);
4394
- }
4395
- }
4396
- if (JSON.stringify(protectedBytes(before)) !== JSON.stringify(protectedBytes(after)))
4397
- throw new Error(`protected region changed in ${file}`);
4398
- const originalHeadings = sections(before).map((item) => item.heading);
4399
- 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));
4400
- if (JSON.stringify(sections(after).map((item) => item.heading)) !== JSON.stringify(expectedHeadings))
4401
- throw new Error(`markdown structure changed in ${file}`);
4402
- tokens += Math.ceil(after.length / 3.5);
4403
- if (after !== before)
4404
- diffs += diff(file, before, after);
4467
+ const items = parseDocsProposalOutput(output);
4468
+ const overBudget = new Map;
4469
+ let result = applyChanges(items, originals, overBudget);
4470
+ while (result.tokens > budget && result.kept.length) {
4471
+ const reason = `over budget: ${result.tokens} > ${budget}`;
4472
+ const latestGrowth = [...result.kept].reverse().find((item) => item.grew);
4473
+ if (latestGrowth)
4474
+ overBudget.set(latestGrowth.index, reason);
4475
+ else
4476
+ for (const item of result.kept)
4477
+ overBudget.set(item.index, reason);
4478
+ result = applyChanges(items, originals, overBudget);
4405
4479
  }
4406
- if (tokens > budget)
4407
- throw new Error(`over budget: ${tokens} > ${budget}`);
4408
- if (!diffs)
4409
- throw new Error("no doc changes proposed");
4410
- return { changes, tokens, diffs };
4480
+ const diffs = FILES.filter((file) => originals[file] !== result.docs[file]).map((file) => diff(file, originals[file], result.docs[file])).join("");
4481
+ return {
4482
+ changes: result.kept.map((item) => item.change),
4483
+ dropped: result.dropped,
4484
+ tokens: result.tokens,
4485
+ diffs
4486
+ };
4411
4487
  }
4412
4488
  function writeDocsProposal(projectDir, output, budget, expected, head) {
4413
4489
  const result = validateDocsProposal(projectDir, output, budget, expected);
4490
+ if (!result.diffs)
4491
+ return { path: null, dropped: result.dropped };
4414
4492
  const dir = proposalDir(projectDir);
4415
4493
  mkdirSync(join(dir, "superseded"), { recursive: true });
4416
4494
  ensureCortexKitArtifactGitignore(projectDir);
@@ -4444,7 +4522,7 @@ ${result.diffs}
4444
4522
  for (const old of listPendingDocsProposals(projectDir))
4445
4523
  if (old !== path)
4446
4524
  renameSync(old, join(dir, "superseded", old.split("/").at(-1) ?? "proposal.md"));
4447
- return path;
4525
+ return { path, dropped: result.dropped };
4448
4526
  }
4449
4527
 
4450
4528
  // src/agents/smart-note-compiler.ts
@@ -11253,19 +11331,13 @@ async function runAgenticTask(config, ctx, helpers) {
11253
11331
  recordInvocation("completed", run.output);
11254
11332
  if (task === "maintain-docs" && docsHashes && changes) {
11255
11333
  try {
11256
- if (parseDocsProposalOutput(String(run.validated)).length === 0) {
11257
- helpers.recordRun("completed", null, { progress: "no corrections proposed" });
11258
- return {
11259
- status: "completed",
11260
- detail: "no corrections proposed",
11261
- schedulePatch: { taskStateJson: JSON.stringify({ head: changes.head }) }
11262
- };
11263
- }
11264
- const path = writeDocsProposal(docsDir, String(run.validated), config.docsMaxTokens ?? 12000, docsHashes, changes.head);
11265
- helpers.recordRun("completed", null, { progress: `proposal: ${path}` });
11334
+ const { path, dropped } = writeDocsProposal(docsDir, String(run.validated), config.docsMaxTokens ?? 12000, docsHashes, changes.head);
11335
+ const outcome = path ? `proposal: ${path}` : "no corrections proposed";
11336
+ const detail = dropped.length ? `${outcome}; dropped ${dropped.map(({ index, reason }) => `entry ${index + 1}: ${reason}`).join("; ")}` : outcome;
11337
+ helpers.recordRun("completed", null, { progress: detail });
11266
11338
  return {
11267
11339
  status: "completed",
11268
- detail: `proposal: ${path}`,
11340
+ detail,
11269
11341
  schedulePatch: { taskStateJson: JSON.stringify({ head: changes.head }) }
11270
11342
  };
11271
11343
  } catch (error) {
package/dist/index.js CHANGED
@@ -143,7 +143,7 @@ import {
143
143
  parameterDescriptionsFor,
144
144
  MagicContextRpcServer,
145
145
  applyHiddenSubagentTemperature
146
- } from "./index-95475ngp.js";
146
+ } from "./index-33bfewqe.js";
147
147
  import {
148
148
  resolveOpenCodeDbPath,
149
149
  openCodeDbPathExists,
@@ -8203,7 +8203,7 @@ var require_src2 = __commonJS(function(exports, module) {
8203
8203
  // package.json
8204
8204
  var package_default = {
8205
8205
  name: "@cortexkit/opencode-magic-context",
8206
- version: "0.49.70",
8206
+ version: "0.49.71",
8207
8207
  type: "module",
8208
8208
  description: "OpenCode plugin for Magic Context — cross-session memory and context management",
8209
8209
  main: "dist/index.js",
@@ -12082,7 +12082,7 @@ async function setup(context) {
12082
12082
  if (claimStorageBackupWarningCheck() && isMagicContextStorageOutsideEngram(storageDir)) {
12083
12083
  log2(`[magic-context] Magic Context storage is at ${storageDir}, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.`);
12084
12084
  }
12085
- const { registerContext } = await import("./context-rcts8w54.js");
12085
+ const { registerContext } = await import("./context-npk0e0aj.js");
12086
12086
  setHarness2("opencode2");
12087
12087
  bindStaleBuildNotice({}, import.meta.url, "opencode2");
12088
12088
  const duties = await registerContext(context);
@@ -32896,7 +32896,7 @@ ${currentDocs?.structure ?? "(read from project)"}
32896
32896
 
32897
32897
  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.
32898
32898
 
32899
- 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.`;
32899
+ 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.`;
32900
32900
  }
32901
32901
  function buildDreamTaskPrompt(task, args) {
32902
32902
  switch (task) {
@@ -34076,23 +34076,35 @@ ${stat}`
34076
34076
  return null;
34077
34077
  }
34078
34078
  }
34079
- function sections(text) {
34080
- const lines = text.split(`
34081
- `);
34079
+ var ATX_HEADING = /^ {0,3}(#{1,6})(?=[ \t]|$)/;
34080
+ function sections(lines) {
34082
34081
  const result = [];
34083
- let fenced = false;
34082
+ const open = [];
34083
+ let fence;
34084
34084
  for (let i = 0;i < lines.length; i++) {
34085
- if (/^\s*(```|~~~)/.test(lines[i]))
34086
- fenced = !fenced;
34087
- if (!fenced && /^#{1,6} \S/.test(lines[i])) {
34088
- if (result.length)
34089
- result[result.length - 1].end = i;
34090
- result.push({ heading: lines[i], text: "", start: i, end: lines.length });
34085
+ const heading = lines[i].replace(/\r$/, "");
34086
+ const marker = heading.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
34087
+ if (fence) {
34088
+ if (marker?.[1].startsWith(fence) && !marker[2].trim())
34089
+ fence = undefined;
34090
+ continue;
34091
34091
  }
34092
+ if (marker && (marker[1][0] === "~" || !marker[2].includes("`"))) {
34093
+ fence = marker[1];
34094
+ continue;
34095
+ }
34096
+ const match = heading.match(ATX_HEADING);
34097
+ if (!match)
34098
+ continue;
34099
+ const level = match[1].length;
34100
+ for (let previous = open.at(-1);previous && previous.level >= level; previous = open.at(-1)) {
34101
+ previous.end = i;
34102
+ open.pop();
34103
+ }
34104
+ const section = { heading, level, start: i, end: lines.length };
34105
+ result.push(section);
34106
+ open.push(section);
34092
34107
  }
34093
- for (const section of result)
34094
- section.text = lines.slice(section.start, section.end).join(`
34095
- `);
34096
34108
  return result;
34097
34109
  }
34098
34110
  function protectedBytes(text) {
@@ -34115,76 +34127,142 @@ function diff(name, before, after) {
34115
34127
  }
34116
34128
  }
34117
34129
  function parseDocsProposalOutput(output) {
34118
- const match = output.match(/```json\s*([\s\S]*?)```/);
34119
- const parsed = JSON.parse(match?.[1] ?? output);
34130
+ let parsed;
34131
+ try {
34132
+ parsed = JSON.parse(output);
34133
+ } catch (error) {
34134
+ const match = output.match(/```json[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```(?=\s|$)/) ?? output.match(/```json\s*([\s\S]*?)```/);
34135
+ if (!match)
34136
+ throw error;
34137
+ parsed = JSON.parse(match[1]);
34138
+ }
34120
34139
  if (!Array.isArray(parsed))
34121
34140
  throw new Error("proposal must be a JSON array");
34122
- const changes = parsed;
34123
- if (changes.some((item) => !item || !FILES.includes(item.file)))
34124
- throw new Error("unknown proposal file");
34141
+ return parsed;
34142
+ }
34143
+ function readChange(item) {
34144
+ if (!item || typeof item !== "object" || Array.isArray(item))
34145
+ return "expected an object";
34146
+ const { file, action, heading, text, reason } = item;
34147
+ if (file !== "ARCHITECTURE.md" && file !== "STRUCTURE.md")
34148
+ return "unknown proposal file";
34149
+ if (action !== "replace" && action !== "add" && action !== "remove")
34150
+ return "invalid action";
34151
+ if (typeof heading !== "string" || /[\r\n]/.test(heading) || !ATX_HEADING.test(heading))
34152
+ return "invalid section heading";
34153
+ if (typeof text !== "string")
34154
+ return "section text must be a string";
34155
+ if (typeof reason !== "string" || !reason.trim() || /[\r\n]/.test(reason))
34156
+ return "expected a one-line reason";
34157
+ return { file, action, heading, text, reason };
34158
+ }
34159
+ function applyChange(before, change) {
34160
+ const lines = before.split(`
34161
+ `);
34162
+ const existing = sections(lines);
34163
+ const index = existing.findIndex((item) => item.heading === change.heading);
34164
+ const replacement = change.action === "remove" ? [] : change.text.trimEnd().split(`
34165
+ `);
34166
+ const inserted = sections(replacement);
34167
+ const wholeSection = inserted[0]?.heading === change.heading && inserted[0].start === 0 && inserted[0].end === replacement.length;
34168
+ const expectedHeadings = existing.map((item) => item.heading);
34169
+ const insertedHeadings = inserted.map((item) => item.heading);
34170
+ let after;
34171
+ if (change.action === "add") {
34172
+ if (index !== -1 || !wholeSection)
34173
+ return `invalid addition ${change.heading}`;
34174
+ after = `${before.endsWith(`
34175
+ `) ? before : `${before}
34176
+ `}
34177
+ ${replacement.join(`
34178
+ `)}
34179
+ `;
34180
+ expectedHeadings.push(...insertedHeadings);
34181
+ } else {
34182
+ if (index === -1)
34183
+ return `missing section ${change.heading}`;
34184
+ if (change.action === "replace" && !wholeSection)
34185
+ return `invalid replacement ${change.heading}`;
34186
+ const section = existing[index];
34187
+ const affected = existing.filter((item) => item.start >= section.start && item.start < section.end);
34188
+ expectedHeadings.splice(index, affected.length, ...insertedHeadings);
34189
+ if (change.action === "replace" && section.end === lines.length && before.endsWith(`
34190
+ `))
34191
+ replacement.push("");
34192
+ lines.splice(section.start, section.end - section.start, ...replacement);
34193
+ after = lines.join(`
34194
+ `);
34195
+ }
34196
+ if (JSON.stringify(protectedBytes(before)) !== JSON.stringify(protectedBytes(after)))
34197
+ return `protected region changed in ${change.file}`;
34198
+ if (JSON.stringify(sections(after.split(`
34199
+ `)).map((item) => item.heading)) !== JSON.stringify(expectedHeadings))
34200
+ return `markdown structure changed in ${change.file}`;
34201
+ if (after === before)
34202
+ return "no doc changes proposed";
34203
+ return { after };
34204
+ }
34205
+ function applyChanges(items, originals, overBudget) {
34206
+ const docs = { ...originals };
34207
+ const kept = [];
34208
+ const dropped = [];
34125
34209
  const seen = new Set;
34126
- for (const change of changes) {
34210
+ for (const [index, item] of items.entries()) {
34211
+ const change = overBudget.get(index) ?? readChange(item);
34212
+ if (typeof change === "string") {
34213
+ dropped.push({ index, reason: change });
34214
+ continue;
34215
+ }
34127
34216
  const key = `${change.file}:${change.heading}`;
34128
- 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))
34129
- throw new Error(`invalid section change in ${change.file}`);
34217
+ const before = docs[change.file];
34218
+ const result = seen.has(key) ? `duplicate section change ${change.heading}` : applyChange(before, change);
34219
+ if (typeof result === "string") {
34220
+ dropped.push({ index, reason: result });
34221
+ continue;
34222
+ }
34223
+ kept.push({ index, change, grew: result.after.length > before.length });
34224
+ docs[change.file] = result.after;
34130
34225
  seen.add(key);
34131
34226
  }
34132
- return changes;
34227
+ const tokens = FILES.reduce((sum, file) => sum + Math.ceil(docs[file].length / 3.5), 0);
34228
+ return { docs, kept, dropped, tokens };
34133
34229
  }
34134
34230
  function validateDocsProposal(projectDir, output, budget, expected) {
34135
- if (Object.entries(expected).some(([name, value]) => docsBaseHashes(projectDir)[name] !== value))
34231
+ const readDoc = (file) => {
34232
+ const path = join8(projectDir, file);
34233
+ return existsSync4(path) ? readFileSync6(path, "utf8") : "";
34234
+ };
34235
+ const originals = {
34236
+ "ARCHITECTURE.md": readDoc("ARCHITECTURE.md"),
34237
+ "STRUCTURE.md": readDoc("STRUCTURE.md")
34238
+ };
34239
+ if (Object.keys(expected).some((name) => !FILES.some((file) => file === name && hash(originals[file]) === expected[name])))
34136
34240
  throw new Error("base drifted");
34137
- const changes = parseDocsProposalOutput(output);
34138
- if (!changes.length)
34139
- throw new Error("empty proposal");
34140
- let tokens = 0;
34141
- let diffs = "";
34142
- for (const file of FILES) {
34143
- const before = existsSync4(join8(projectDir, file)) ? readFileSync6(join8(projectDir, file), "utf8") : "";
34144
- let after = before;
34145
- for (const change of changes.filter((item) => item.file === file)) {
34146
- const section = sections(after).find((item) => item.heading === change.heading);
34147
- if (change.action === "add") {
34148
- if (section || !change.text.startsWith(`${change.heading}
34149
- `))
34150
- throw new Error(`invalid addition ${change.heading}`);
34151
- after += `${after.endsWith(`
34152
- `) ? "" : `
34153
- `}
34154
- ${change.text.trimEnd()}
34155
- `;
34156
- } else {
34157
- if (!section)
34158
- throw new Error(`missing section ${change.heading}`);
34159
- if (change.action === "replace" && (!change.text.startsWith(`${change.heading}
34160
- `) || sections(change.text).length !== 1))
34161
- throw new Error(`invalid replacement ${change.heading}`);
34162
- const lines = after.split(`
34163
- `);
34164
- lines.splice(section.start, section.end - section.start, ...change.action === "remove" ? [] : change.text.trimEnd().split(`
34165
- `));
34166
- after = lines.join(`
34167
- `);
34168
- }
34169
- }
34170
- if (JSON.stringify(protectedBytes(before)) !== JSON.stringify(protectedBytes(after)))
34171
- throw new Error(`protected region changed in ${file}`);
34172
- const originalHeadings = sections(before).map((item) => item.heading);
34173
- 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));
34174
- if (JSON.stringify(sections(after).map((item) => item.heading)) !== JSON.stringify(expectedHeadings))
34175
- throw new Error(`markdown structure changed in ${file}`);
34176
- tokens += Math.ceil(after.length / 3.5);
34177
- if (after !== before)
34178
- diffs += diff(file, before, after);
34241
+ const items = parseDocsProposalOutput(output);
34242
+ const overBudget = new Map;
34243
+ let result = applyChanges(items, originals, overBudget);
34244
+ while (result.tokens > budget && result.kept.length) {
34245
+ const reason = `over budget: ${result.tokens} > ${budget}`;
34246
+ const latestGrowth = [...result.kept].reverse().find((item) => item.grew);
34247
+ if (latestGrowth)
34248
+ overBudget.set(latestGrowth.index, reason);
34249
+ else
34250
+ for (const item of result.kept)
34251
+ overBudget.set(item.index, reason);
34252
+ result = applyChanges(items, originals, overBudget);
34179
34253
  }
34180
- if (tokens > budget)
34181
- throw new Error(`over budget: ${tokens} > ${budget}`);
34182
- if (!diffs)
34183
- throw new Error("no doc changes proposed");
34184
- return { changes, tokens, diffs };
34254
+ const diffs = FILES.filter((file) => originals[file] !== result.docs[file]).map((file) => diff(file, originals[file], result.docs[file])).join("");
34255
+ return {
34256
+ changes: result.kept.map((item) => item.change),
34257
+ dropped: result.dropped,
34258
+ tokens: result.tokens,
34259
+ diffs
34260
+ };
34185
34261
  }
34186
34262
  function writeDocsProposal(projectDir, output, budget, expected, head) {
34187
34263
  const result = validateDocsProposal(projectDir, output, budget, expected);
34264
+ if (!result.diffs)
34265
+ return { path: null, dropped: result.dropped };
34188
34266
  const dir = proposalDir(projectDir);
34189
34267
  mkdirSync(join8(dir, "superseded"), { recursive: true });
34190
34268
  ensureCortexKitArtifactGitignore(projectDir);
@@ -34218,7 +34296,7 @@ ${result.diffs}
34218
34296
  for (const old of listPendingDocsProposals(projectDir))
34219
34297
  if (old !== path)
34220
34298
  renameSync(old, join8(dir, "superseded", old.split("/").at(-1) ?? "proposal.md"));
34221
- return path;
34299
+ return { path, dropped: result.dropped };
34222
34300
  }
34223
34301
 
34224
34302
  // src/agents/smart-note-compiler.ts
@@ -40026,19 +40104,13 @@ async function runAgenticTask(config, ctx, helpers) {
40026
40104
  recordInvocation("completed", run.output);
40027
40105
  if (task === "maintain-docs" && docsHashes && changes) {
40028
40106
  try {
40029
- if (parseDocsProposalOutput(String(run.validated)).length === 0) {
40030
- helpers.recordRun("completed", null, { progress: "no corrections proposed" });
40031
- return {
40032
- status: "completed",
40033
- detail: "no corrections proposed",
40034
- schedulePatch: { taskStateJson: JSON.stringify({ head: changes.head }) }
40035
- };
40036
- }
40037
- const path = writeDocsProposal(docsDir, String(run.validated), config.docsMaxTokens ?? 12000, docsHashes, changes.head);
40038
- helpers.recordRun("completed", null, { progress: `proposal: ${path}` });
40107
+ const { path, dropped } = writeDocsProposal(docsDir, String(run.validated), config.docsMaxTokens ?? 12000, docsHashes, changes.head);
40108
+ const outcome = path ? `proposal: ${path}` : "no corrections proposed";
40109
+ const detail = dropped.length ? `${outcome}; dropped ${dropped.map(({ index, reason }) => `entry ${index + 1}: ${reason}`).join("; ")}` : outcome;
40110
+ helpers.recordRun("completed", null, { progress: detail });
40039
40111
  return {
40040
40112
  status: "completed",
40041
- detail: `proposal: ${path}`,
40113
+ detail,
40042
40114
  schedulePatch: { taskStateJson: JSON.stringify({ head: changes.head }) }
40043
40115
  };
40044
40116
  } catch (error) {
package/dist/v2/server.js CHANGED
@@ -7875,7 +7875,7 @@ var require_src2 = __commonJS(function(exports, module) {
7875
7875
  // package.json
7876
7876
  var package_default = {
7877
7877
  name: "@cortexkit/opencode-magic-context",
7878
- version: "0.49.70",
7878
+ version: "0.49.71",
7879
7879
  type: "module",
7880
7880
  description: "OpenCode plugin for Magic Context — cross-session memory and context management",
7881
7881
  main: "dist/index.js",
@@ -8196,7 +8196,7 @@ async function setup(context) {
8196
8196
  if (claimStorageBackupWarningCheck() && isMagicContextStorageOutsideEngram(storageDir)) {
8197
8197
  log2(`[magic-context] Magic Context storage is at ${storageDir}, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.`);
8198
8198
  }
8199
- const { registerContext } = await import("./context-wv122q62.js");
8199
+ const { registerContext } = await import("./context-vehx9ha8.js");
8200
8200
  setHarness2("opencode2");
8201
8201
  bindStaleBuildNotice({}, import.meta.url, "opencode2");
8202
8202
  const duties = await registerContext(context);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-magic-context",
3
- "version": "0.49.70",
3
+ "version": "0.49.71",
4
4
  "type": "module",
5
5
  "description": "OpenCode plugin for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",