harness-everything 1.2.1 → 1.3.0

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 (55) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +31 -0
  4. package/benchmarks/results/live-host/agy-2026-11-26-516-read-only/README.md +12 -0
  5. package/benchmarks/results/live-host/agy-2026-11-26-516-read-only/capture.sanitized.jsonl +5 -0
  6. package/benchmarks/results/live-host/codex-2026-11-26-488-post-tool-use/README.md +25 -0
  7. package/benchmarks/results/live-host/codex-2026-11-26-488-post-tool-use/capture.sanitized.jsonl +10 -0
  8. package/ci/fixtures/468-dispatch/agy-quota-PROVENANCE.md +19 -0
  9. package/ci/fixtures/468-dispatch/agy-quota-direct-individual.stderr +2 -0
  10. package/ci/fixtures/468-dispatch/agy-quota-direct-third-party.stderr +2 -0
  11. package/ci/fixtures/468-dispatch/agy-quota-exec-individual.log +3 -0
  12. package/ci/mechanism-2am-observations-session-import.test.js +1 -0
  13. package/ci/mechanism-2w-platform-compatibility.test.js +1 -2
  14. package/ci/mechanism-34-observations.test.js +37 -1
  15. package/ci/mechanism-397-opencode-observations.test.js +4 -3
  16. package/ci/mechanism-468-dispatch-cli.test.js +1496 -4
  17. package/ci/mechanism-516-windows-verify-and-shell.test.js +74 -19
  18. package/ci/mechanism-548-bigint-identity.test.js +531 -0
  19. package/ci/mechanism-error-ledger-oracle.test.js +786 -3
  20. package/ci/mechanism-error-ledger-scan.test.js +981 -0
  21. package/ci/mechanism-report-writer.test.js +47 -1
  22. package/ci/mechanism-system-one-cycle.test.js +47 -2
  23. package/ci/openai-plugin-submission.test.js +26 -8
  24. package/docs/error-handling/details/c8-dispatch-cli.md +109 -13
  25. package/docs/openai-plugin.md +6 -10
  26. package/docs/platform-capabilities.md +15 -0
  27. package/docs/routing.md +2 -0
  28. package/error-ledger-bootstrap/SKILL.md +1 -1
  29. package/error-ledger-bootstrap/references/workflow.md +42 -7
  30. package/error-ledger-bootstrap/scripts/promote.js +8 -6
  31. package/error-ledger-bootstrap/scripts/scan.js +525 -12
  32. package/harness-everything/SKILL.md +1 -1
  33. package/harness-everything/scripts/kernel-router.js +3 -2
  34. package/hooks/scripts/state-persist.js +6 -1
  35. package/opencode-plugin/plugin.json +1 -1
  36. package/package.json +1 -1
  37. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  38. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  39. package/plugins/harness-everything/hooks/scripts/state-persist.js +6 -1
  40. package/plugins/harness-everything/plugin.json +1 -1
  41. package/plugins/harness-everything/skills/error-ledger-bootstrap/SKILL.md +1 -1
  42. package/plugins/harness-everything/skills/error-ledger-bootstrap/references/workflow.md +42 -7
  43. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/promote.js +8 -6
  44. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/scan.js +525 -12
  45. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  46. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +3 -2
  47. package/sbom.cdx.json +7 -7
  48. package/scripts/build-openai-submission.js +8 -4
  49. package/scripts/dispatch.js +499 -87
  50. package/scripts/error-ledger-oracle.js +521 -27
  51. package/scripts/errors-sync.js +4 -3
  52. package/scripts/report-writer.js +4 -3
  53. package/submission/openai/README.md +9 -14
  54. package/submission/openai/listing.json +1 -1
  55. package/submission/openai/test-cases.json +1 -1
@@ -515,10 +515,11 @@ function savedIndex(index) {
515
515
  function indexState(index) {
516
516
  let fd;
517
517
  try {
518
- const current = fs.lstatSync(index);
518
+ // Keep 64-bit device/file IDs exact (Windows IDs can exceed Number's safe integer range).
519
+ const current = fs.lstatSync(index, { bigint: true });
519
520
  if (current.isSymbolicLink() || !current.isFile()) throw new Error('index was replaced with a non-regular file');
520
521
  fd = fs.openSync(index, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
521
- const opened = fs.fstatSync(fd);
522
+ const opened = fs.fstatSync(fd, { bigint: true });
522
523
  if (!opened.isFile() || opened.dev !== current.dev || opened.ino !== current.ino) {
523
524
  throw new Error('index changed while it was being read');
524
525
  }
@@ -544,13 +545,14 @@ function writePreviousIndex(index, saved, current, expected) {
544
545
  }
545
546
 
546
547
  const dir = path.dirname(index);
548
+ const mode = Number(saved.stat.mode) & 0o777;
547
549
  let temporary;
548
550
  let fd;
549
551
  try {
550
552
  for (let attempt = 0; attempt < 5; attempt++) {
551
553
  temporary = path.join(dir, `.${INDEX}.${process.pid}.${crypto.randomBytes(8).toString('hex')}.tmp`);
552
554
  try {
553
- fd = fs.openSync(temporary, 'wx', saved.stat.mode & 0o777);
555
+ fd = fs.openSync(temporary, 'wx', mode);
554
556
  break;
555
557
  } catch (error) {
556
558
  temporary = undefined;
@@ -558,7 +560,7 @@ function writePreviousIndex(index, saved, current, expected) {
558
560
  }
559
561
  }
560
562
  if (fd === undefined) throw new Error('could not allocate a temporary rollback index');
561
- fs.fchmodSync(fd, saved.stat.mode & 0o777);
563
+ fs.fchmodSync(fd, mode);
562
564
  fs.writeFileSync(fd, saved.bytes);
563
565
  const openFd = fd;
564
566
  fd = undefined;
@@ -615,7 +617,7 @@ function rollback(context, saved, destination, identity, beforeNames) {
615
617
  }
616
618
  if (identity) {
617
619
  try {
618
- const current = fs.lstatSync(destination);
620
+ const current = fs.lstatSync(destination, { bigint: true });
619
621
  if (current.dev !== identity.dev || current.ino !== identity.ino || current.isSymbolicLink()) {
620
622
  problems.push('new record was replaced by another writer');
621
623
  } else fs.unlinkSync(destination);
@@ -662,7 +664,7 @@ function promote(context) {
662
664
  let recordFd;
663
665
  try {
664
666
  recordFd = fs.openSync(destination.destination, 'wx', 0o644);
665
- identity = fs.fstatSync(recordFd);
667
+ identity = fs.fstatSync(recordFd, { bigint: true });
666
668
  fs.writeFileSync(recordFd, text, 'utf8');
667
669
  fs.closeSync(recordFd);
668
670
  recordFd = undefined;
@@ -167,6 +167,48 @@ function repoFiles(root) {
167
167
  .split('\0').filter(Boolean).map(normalizedRepoPath);
168
168
  }
169
169
 
170
+ function isTrackedRegularFile(root, site) {
171
+ if (!site || site === '.' || site.endsWith('/') || path.posix.isAbsolute(site) ||
172
+ /^[A-Za-z]:/.test(site) || site.includes('\\') || site.split('/').includes('..')) {
173
+ return false;
174
+ }
175
+ const candidate = path.resolve(root, site.split('/').join(path.sep));
176
+ if (!isWithin(root, candidate)) return false;
177
+ let stat;
178
+ try {
179
+ stat = fs.lstatSync(candidate);
180
+ } catch (_) {
181
+ return false;
182
+ }
183
+ if (stat.isSymbolicLink() || !stat.isFile()) return false;
184
+ let resolved;
185
+ try {
186
+ resolved = canonical(candidate);
187
+ } catch (_) {
188
+ return false;
189
+ }
190
+ if (!isWithin(root, resolved)) return false;
191
+ try {
192
+ return fs.statSync(resolved).isFile();
193
+ } catch (_) {
194
+ return false;
195
+ }
196
+ }
197
+
198
+ function trackedRegularFiles(root) {
199
+ const entries = git(root, ['ls-files', '--cached', '--stage', '-z']).split('\0').filter(Boolean);
200
+ const tracked = new Set();
201
+ for (const entry of entries) {
202
+ const tab = entry.indexOf('\t');
203
+ if (tab === -1) continue;
204
+ const mode = entry.slice(0, entry.indexOf(' '));
205
+ if (mode !== '100644' && mode !== '100755') continue;
206
+ const site = normalizedRepoPath(entry.slice(tab + 1));
207
+ if (isTrackedRegularFile(root, site)) tracked.add(site);
208
+ }
209
+ return tracked;
210
+ }
211
+
170
212
  function safeRead(file) {
171
213
  try {
172
214
  if (fs.lstatSync(file).isSymbolicLink()) return null;
@@ -192,10 +234,23 @@ function walkMarkdown(directory) {
192
234
  return found;
193
235
  }
194
236
 
237
+ function isMemoryIndex(file) {
238
+ return /^memory\.md$/i.test(path.basename(file));
239
+ }
240
+
241
+ function isRegularFile(file) {
242
+ try {
243
+ const stat = fs.lstatSync(file);
244
+ return !stat.isSymbolicLink() && stat.isFile();
245
+ } catch (_) {
246
+ return false;
247
+ }
248
+ }
249
+
195
250
  function flatMarkdown(directory) {
196
251
  try {
197
252
  return fs.readdirSync(directory, { withFileTypes: true })
198
- .filter(entry => entry.isFile() && entry.name.toLowerCase().endsWith('.md'))
253
+ .filter(entry => entry.isFile() && entry.name.toLowerCase().endsWith('.md') && !isMemoryIndex(entry.name))
199
254
  .map(entry => path.join(directory, entry.name))
200
255
  .sort((a, b) => a.localeCompare(b));
201
256
  } catch (_) {
@@ -249,12 +304,373 @@ function lessonSites(text, knownFiles) {
249
304
  return [...sites].sort();
250
305
  }
251
306
 
252
- function isLesson(text, file) {
307
+ const MEMORY_WRAPPER_PAIRS = [
308
+ ['(', ')'],
309
+ ['[', ']'],
310
+ ['{', '}'],
311
+ ['<', '>'],
312
+ ['"', '"'],
313
+ ["'", "'"],
314
+ ['`', '`'],
315
+ ['|', '|']
316
+ ];
317
+
318
+ function isForbiddenMemoryToken(value) {
319
+ return /^[a-z][a-z0-9+.-]*:\/\//i.test(value) ||
320
+ /^file:\//i.test(value) ||
321
+ value.startsWith('/') ||
322
+ value.startsWith('\\') ||
323
+ value.startsWith('./') ||
324
+ /^[A-Za-z]:/.test(value) ||
325
+ value.includes('\\') ||
326
+ /(?:^|\/)\.\.(?:\/|$)/.test(value);
327
+ }
328
+
329
+ function stripMemoryPunctuation(value) {
330
+ return value.replace(/[,;:!?]+$/, '').replace(/\.$/, '');
331
+ }
332
+
333
+ function resolveMemorySiteToken(token, trackedFiles) {
334
+ let current = token;
335
+ while (current) {
336
+ if (isForbiddenMemoryToken(current)) return null;
337
+ if (trackedFiles.has(current)) return current;
338
+
339
+ const depunct = stripMemoryPunctuation(current);
340
+ if (depunct !== current) {
341
+ current = depunct;
342
+ continue;
343
+ }
344
+
345
+ const linkSep = current.indexOf('](');
346
+ if (linkSep !== -1 && current.endsWith(')')) {
347
+ return resolveMemorySiteToken(current.slice(linkSep + 2, -1), trackedFiles);
348
+ }
349
+
350
+ let peeled = false;
351
+ for (const [open, close] of MEMORY_WRAPPER_PAIRS) {
352
+ if (current.length >= 2 && current.startsWith(open) && current.endsWith(close)) {
353
+ current = current.slice(1, -1);
354
+ peeled = true;
355
+ break;
356
+ }
357
+ }
358
+ if (peeled) continue;
359
+
360
+ if (/^["'`<>(\[{|]/.test(current)) {
361
+ current = current.slice(1);
362
+ continue;
363
+ }
364
+ if (/["'`<>)\]}|]$/.test(current)) {
365
+ current = current.slice(0, -1);
366
+ continue;
367
+ }
368
+ break;
369
+ }
370
+ return null;
371
+ }
372
+
373
+ function memorySites(text, trackedFiles) {
374
+ if (!trackedFiles || !trackedFiles.size) return [];
375
+ const sites = new Set();
376
+ for (const raw of String(text || '').split(/\s+/)) {
377
+ if (!raw) continue;
378
+ const site = resolveMemorySiteToken(raw, trackedFiles);
379
+ if (site) sites.add(site);
380
+ }
381
+ return [...sites].sort();
382
+ }
383
+
384
+ function consumeQuotedScalar(lines, lineIdx, startCol) {
385
+ const quote = lines[lineIdx][startCol];
386
+ let value = '';
387
+ for (let li = lineIdx; li < lines.length; li++) {
388
+ const line = lines[li];
389
+ let col = li === lineIdx ? startCol + 1 : 0;
390
+ while (col < line.length) {
391
+ const ch = line[col];
392
+ if (quote === '"' && ch === '\\') {
393
+ if (col + 1 >= line.length) {
394
+ col += 1;
395
+ break;
396
+ }
397
+ const next = line[col + 1];
398
+ value += next === 'n' ? '\n' : next === 't' ? '\t' : next === 'r' ? '\r' : next;
399
+ col += 2;
400
+ continue;
401
+ }
402
+ if (quote === "'" && ch === "'" && line[col + 1] === "'") {
403
+ value += "'";
404
+ col += 2;
405
+ continue;
406
+ }
407
+ if (ch === quote) {
408
+ const trailing = line.slice(col + 1);
409
+ if (!/^(?:[ \t]+#.*|[ \t]*)$/.test(trailing)) return { ok: false };
410
+ return { ok: true, value, endLine: li, multiline: li !== lineIdx };
411
+ }
412
+ value += ch;
413
+ col += 1;
414
+ }
415
+ if (li < lines.length - 1) value += '\n';
416
+ }
417
+ return { ok: false };
418
+ }
419
+
420
+ function parseTypeScalar(rawValue) {
421
+ const trimmed = rawValue.trimStart();
422
+ if (!trimmed || trimmed.startsWith('#')) return { ok: false };
423
+ if (trimmed[0] === '"' || trimmed[0] === "'") {
424
+ const quoted = consumeQuotedScalar([trimmed], 0, 0);
425
+ if (!quoted.ok || quoted.multiline || !quoted.value.trim()) return { ok: false };
426
+ return { ok: true, value: quoted.value };
427
+ }
428
+ if (/^[[\]{}|>&*!]/.test(trimmed)) return { ok: false };
429
+ const commentIdx = trimmed.search(/[ \t]+#/);
430
+ const plain = (commentIdx === -1 ? trimmed : trimmed.slice(0, commentIdx)).trimEnd();
431
+ if (!plain || plain === 'null' || plain === '~' || /^[?:,-](?:[ \t]|$)|:[ \t]/.test(plain)) {
432
+ return { ok: false };
433
+ }
434
+ return { ok: true, value: plain };
435
+ }
436
+
437
+ function parseMappingLine(content) {
438
+ if (content[0] === '"' || content[0] === "'") {
439
+ const quote = content[0];
440
+ let key = '';
441
+ let col = 1;
442
+ while (col < content.length) {
443
+ const ch = content[col];
444
+ if (quote === '"' && ch === '\\') {
445
+ if (col + 1 >= content.length) return null;
446
+ key += content[col + 1];
447
+ col += 2;
448
+ continue;
449
+ }
450
+ if (quote === "'" && ch === "'" && content[col + 1] === "'") {
451
+ key += "'";
452
+ col += 2;
453
+ continue;
454
+ }
455
+ if (ch === quote) {
456
+ const rest = /^([ \t]*):(?:([ \t]+.*)|[ \t]*)$/.exec(content.slice(col + 1));
457
+ if (!rest) return null;
458
+ return { key, rawValue: rest[2] || '' };
459
+ }
460
+ key += ch;
461
+ col += 1;
462
+ }
463
+ return null;
464
+ }
465
+ const match = /^([^:#\[\]{}"'\t-][^:\t]*?)[ \t]*:(?:([ \t]+.*)|[ \t]*)$/.exec(content);
466
+ if (!match) return null;
467
+ return { key: match[1].trim(), rawValue: match[2] || '' };
468
+ }
469
+
470
+ function consumeOtherValue(lines, lineIdx, keyIndent, rawValue) {
471
+ const trimmed = rawValue.trimStart();
472
+ if (!trimmed || trimmed.startsWith('#')) {
473
+ return { ok: true, endLine: lineIdx, allowsNested: true };
474
+ }
475
+ if (/^[|>](?:[+-]?\d*|\d*[+-]?)?(?:[ \t]+#.*|[ \t]*)$/.test(trimmed)) {
476
+ let end = lineIdx;
477
+ for (let j = lineIdx + 1; j < lines.length; j++) {
478
+ if (/^[ \t]*$/.test(lines[j])) {
479
+ end = j;
480
+ continue;
481
+ }
482
+ const spaces = /^ */.exec(lines[j])[0].length;
483
+ if (spaces > keyIndent) {
484
+ end = j;
485
+ continue;
486
+ }
487
+ break;
488
+ }
489
+ return { ok: true, endLine: end, allowsNested: false };
490
+ }
491
+ if (trimmed[0] === '"' || trimmed[0] === "'") {
492
+ const startCol = lines[lineIdx].length - trimmed.length;
493
+ const quoted = consumeQuotedScalar(lines, lineIdx, startCol);
494
+ if (!quoted.ok) return { ok: false };
495
+ return { ok: true, endLine: quoted.endLine, allowsNested: false };
496
+ }
497
+ return { ok: true, endLine: lineIdx, allowsNested: false };
498
+ }
499
+
500
+ function consumeNestedLine(lines, lineIdx, indent, content) {
501
+ const parsed = parseMappingLine(content);
502
+ if (!parsed) return { ok: true, endLine: lineIdx };
503
+ const consumed = consumeOtherValue(lines, lineIdx, indent, parsed.rawValue);
504
+ if (!consumed.ok) return { ok: false };
505
+ return { ok: true, endLine: consumed.endLine };
506
+ }
507
+
508
+ function parseMemoryFrontmatter(text) {
509
+ const source = String(text || '').replace(/^\uFEFF/, '');
510
+ const lines = source.split(/\r?\n/);
511
+ if (!/^---[ \t]*$/.test(lines[0])) {
512
+ return { state: 'untyped', body: source };
513
+ }
514
+ let closeIdx = -1;
515
+ for (let i = 1; i < lines.length; i++) {
516
+ if (/^---[ \t]*$/.test(lines[i])) {
517
+ closeIdx = i;
518
+ break;
519
+ }
520
+ }
521
+ if (closeIdx === -1) return { state: 'malformed', body: '' };
522
+
523
+ const fmLines = lines.slice(1, closeIdx);
524
+ const body = lines.slice(closeIdx + 1).join('\n');
525
+ const topTypes = [];
526
+ const metaTypes = [];
527
+ let inMetadata = false;
528
+ let metaChildIndent = null;
529
+ let topAllowsNested = false;
530
+ let metaChildAllowsNested = false;
531
+ let metaCount = 0;
532
+
533
+ for (let i = 0; i < fmLines.length; i++) {
534
+ const line = fmLines[i];
535
+ if (/^[ \t]*(?:#.*)?$/.test(line)) continue;
536
+ const indentMatch = /^([ \t]*)/.exec(line);
537
+ if (indentMatch[1].includes('\t')) return { state: 'malformed', body };
538
+ const indent = indentMatch[1].length;
539
+ const content = line.slice(indent);
540
+
541
+ if (inMetadata) {
542
+ if (indent === 0) {
543
+ inMetadata = false;
544
+ metaChildIndent = null;
545
+ metaChildAllowsNested = false;
546
+ } else {
547
+ if (metaChildIndent === null) {
548
+ if (/^-(?:[ \t]|$)/.test(content)) return { state: 'malformed', body };
549
+ metaChildIndent = indent;
550
+ }
551
+ if (indent < metaChildIndent) return { state: 'malformed', body };
552
+ if (indent > metaChildIndent) {
553
+ if (!metaChildAllowsNested) return { state: 'malformed', body };
554
+ const nested = consumeNestedLine(fmLines, i, indent, content);
555
+ if (!nested.ok) return { state: 'malformed', body };
556
+ i = nested.endLine;
557
+ continue;
558
+ }
559
+ if (metaChildAllowsNested && /^-(?:[ \t]|$)/.test(content)) continue;
560
+ metaChildAllowsNested = false;
561
+ const entry = parseMappingLine(content);
562
+ if (!entry) return { state: 'malformed', body };
563
+ if (entry.key === 'type') {
564
+ const scalar = parseTypeScalar(entry.rawValue);
565
+ if (!scalar.ok) return { state: 'malformed', body };
566
+ metaTypes.push(scalar.value.toLowerCase());
567
+ } else {
568
+ const consumed = consumeOtherValue(fmLines, i, indent, entry.rawValue);
569
+ if (!consumed.ok) return { state: 'malformed', body };
570
+ i = consumed.endLine;
571
+ metaChildAllowsNested = consumed.allowsNested;
572
+ }
573
+ continue;
574
+ }
575
+ }
576
+
577
+ if (indent > 0) {
578
+ if (!topAllowsNested) return { state: 'malformed', body };
579
+ const nested = consumeNestedLine(fmLines, i, indent, content);
580
+ if (!nested.ok) return { state: 'malformed', body };
581
+ i = nested.endLine;
582
+ continue;
583
+ }
584
+ if (topAllowsNested && /^-(?:[ \t]|$)/.test(content)) continue;
585
+ topAllowsNested = false;
586
+ const entry = parseMappingLine(content);
587
+ if (!entry) return { state: 'malformed', body };
588
+ if (entry.key === 'type') {
589
+ const scalar = parseTypeScalar(entry.rawValue);
590
+ if (!scalar.ok) return { state: 'malformed', body };
591
+ topTypes.push(scalar.value.toLowerCase());
592
+ } else if (entry.key === 'metadata') {
593
+ const trimmed = entry.rawValue.trimStart();
594
+ if (trimmed && !trimmed.startsWith('#')) return { state: 'malformed', body };
595
+ metaCount += 1;
596
+ if (metaCount > 1) return { state: 'malformed', body };
597
+ inMetadata = true;
598
+ metaChildIndent = null;
599
+ metaChildAllowsNested = false;
600
+ } else {
601
+ const consumed = consumeOtherValue(fmLines, i, 0, entry.rawValue);
602
+ if (!consumed.ok) return { state: 'malformed', body };
603
+ i = consumed.endLine;
604
+ topAllowsNested = consumed.allowsNested;
605
+ }
606
+ }
607
+
608
+ if (topTypes.length > 1 || metaTypes.length > 1) {
609
+ return { state: 'malformed', body };
610
+ }
611
+ if (topTypes.length === 1 && metaTypes.length === 1) {
612
+ if (topTypes[0] !== metaTypes[0]) return { state: 'conflicting', body };
613
+ return { state: topTypes[0] === 'feedback' ? 'feedback' : 'explicit-other', body };
614
+ }
615
+ const single = topTypes[0] ?? metaTypes[0];
616
+ if (single !== undefined) {
617
+ return { state: single === 'feedback' ? 'feedback' : 'explicit-other', body };
618
+ }
619
+ return { state: 'untyped', body };
620
+ }
621
+
622
+ function stripFencedCodeBlocks(text) {
623
+ const lines = text.split(/\r?\n/);
624
+ const kept = [];
625
+ let fenceChar = null;
626
+ let fenceLen = 0;
627
+ for (const line of lines) {
628
+ if (!fenceChar) {
629
+ const open = /^[ \t]{0,3}(`{3,}|~{3,})(.*)$/.exec(line);
630
+ if (open && (open[1][0] === '~' || !open[2].includes('`'))) {
631
+ fenceChar = open[1][0];
632
+ fenceLen = open[1].length;
633
+ continue;
634
+ }
635
+ kept.push(line);
636
+ } else {
637
+ const close = new RegExp(`^[ \\t]{0,3}${fenceChar}{${fenceLen},}[ \\t]*$`);
638
+ if (close.test(line)) {
639
+ fenceChar = null;
640
+ fenceLen = 0;
641
+ }
642
+ }
643
+ }
644
+ return kept.join('\n');
645
+ }
646
+
647
+ function hasPairedWhyHowHeadings(body) {
648
+ const why = /^[ \t]{0,3}(?:#{1,6}[ \t]*why(?:\s*:|\s*$)|(?:\*\*why:\*\*|\*\*why\*\*:|__why:__|__why__:)(?:[ \t]|$)|(?:\*\*why\*\*|__why__)[ \t]*$)/im;
649
+ const how = /^[ \t]{0,3}(?:#{1,6}[ \t]*how[ \t]+to[ \t]+apply(?:\s*:|\s*$)|(?:\*\*how[ \t]+to[ \t]+apply:\*\*|\*\*how[ \t]+to[ \t]+apply\*\*:|__how[ \t]+to[ \t]+apply:__|__how[ \t]+to[ \t]+apply__:)(?:[ \t]|$)|(?:\*\*how[ \t]+to[ \t]+apply\*\*|__how[ \t]+to[ \t]+apply__)[ \t]*$)/im;
650
+ return why.test(body) && how.test(body);
651
+ }
652
+
653
+ function isInstructionLesson(text, file) {
253
654
  const frontmatter = /^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
254
655
  const feedback = frontmatter && /^type:\s*['"]?feedback(?:['"]?\s|$)/mi.test(frontmatter[1]);
255
656
  return Boolean(feedback || /^lesson-/i.test(path.basename(file)) || /^#{1,6}\s*(?:cue|lesson)\b/im.test(text));
256
657
  }
257
658
 
659
+ function isMemoryLesson(text, file) {
660
+ if (isMemoryIndex(file)) return false;
661
+ const parsed = parseMemoryFrontmatter(text);
662
+ if (parsed.state === 'feedback') return true;
663
+ if (parsed.state !== 'untyped') return false;
664
+ if (/^(?:lesson|feedback)-/i.test(path.basename(file))) return true;
665
+ const cleanBody = stripFencedCodeBlocks(parsed.body);
666
+ if (/^[ \t]{0,3}#{1,6}[ \t]*(?:cue|lesson)\b/im.test(cleanBody)) return true;
667
+ return hasPairedWhyHowHeadings(cleanBody);
668
+ }
669
+
670
+ function isLesson(text, file, type = 'instruction') {
671
+ return type === 'memory' ? isMemoryLesson(text, file) : isInstructionLesson(text, file);
672
+ }
673
+
258
674
  function publicText(value, root, home) {
259
675
  let text = String(value || '');
260
676
  for (const [absolute, label] of [[root, '<repo>'], [home, '<home>']]) {
@@ -295,8 +711,9 @@ function makeCandidate({ title, signature, sites, sources }) {
295
711
  function candidatesFromFiles(files, type, root, home, knownFiles, privateInput = false) {
296
712
  const candidates = [];
297
713
  for (const file of files) {
714
+ if (type === 'memory' && isMemoryIndex(file)) continue;
298
715
  const text = safeRead(file);
299
- if (text === null || !isLesson(text, file)) continue;
716
+ if (text === null || !isLesson(text, file, type)) continue;
300
717
  const privateSource = type === 'memory' || privateInput || !isWithin(root, path.resolve(file));
301
718
  const title = privateSource ? `Local ${type} lead` :
302
719
  shortTitle(markdownTitle(text) || path.basename(file, path.extname(file)), root, home);
@@ -304,26 +721,109 @@ function candidatesFromFiles(files, type, root, home, knownFiles, privateInput =
304
721
  candidates.push(makeCandidate({
305
722
  title,
306
723
  signature: slug(title),
307
- sites: lessonSites(text, privateSource ? knownFiles : undefined),
724
+ sites: type === 'memory'
725
+ ? memorySites(text, knownFiles)
726
+ : lessonSites(text, privateSource ? knownFiles : undefined),
308
727
  sources: [{ type, ref }]
309
728
  }));
310
729
  }
311
730
  return candidates;
312
731
  }
313
732
 
314
- function autoMemory(root, home) {
315
- const slugDir = path.join(home, '.claude', 'projects', path.resolve(root).replace(/[^a-z0-9]/gi, '-'));
733
+ function samePath(left, right, pathApi) {
734
+ return isWithin(left, right, pathApi) && isWithin(right, left, pathApi);
735
+ }
736
+
737
+ function parseWorktreeList(raw) {
738
+ const entries = [];
739
+ let current = null;
740
+ for (const token of raw.split('\0')) {
741
+ if (token === '') {
742
+ if (current) entries.push(current);
743
+ current = null;
744
+ continue;
745
+ }
746
+ if (token.startsWith('worktree ')) {
747
+ if (current) entries.push(current);
748
+ try {
749
+ current = { root: canonical(token.slice(9)), bare: false };
750
+ } catch (_) {
751
+ current = null;
752
+ }
753
+ } else if (current && token === 'bare') {
754
+ current.bare = true;
755
+ }
756
+ }
757
+ if (current) entries.push(current);
758
+ return entries;
759
+ }
760
+
761
+ function mainWorktreeRoot(root) {
762
+ let commonRaw;
763
+ let gitDirRaw;
764
+ try {
765
+ commonRaw = git(root, ['rev-parse', '--git-common-dir']).trim();
766
+ gitDirRaw = git(root, ['rev-parse', '--git-dir']).trim();
767
+ } catch (_) {
768
+ return null;
769
+ }
770
+ if (!commonRaw || !gitDirRaw) return null;
771
+ let commonDir;
772
+ let gitDir;
773
+ try {
774
+ commonDir = canonical(path.resolve(root, commonRaw));
775
+ gitDir = canonical(path.resolve(root, gitDirRaw));
776
+ } catch (_) {
777
+ return null;
778
+ }
779
+ if (samePath(commonDir, gitDir)) return null;
780
+ if (path.basename(commonDir) !== '.git') return null;
781
+ const candidate = path.dirname(commonDir);
782
+ let mainRoot;
783
+ try {
784
+ if (!fs.statSync(candidate).isDirectory()) return null;
785
+ mainRoot = canonical(candidate);
786
+ } catch (_) {
787
+ return null;
788
+ }
789
+ if (samePath(mainRoot, root)) return null;
790
+ let worktreeRaw;
791
+ try {
792
+ worktreeRaw = git(root, ['worktree', 'list', '--porcelain', '-z']);
793
+ } catch (_) {
794
+ return null;
795
+ }
796
+ const registered = parseWorktreeList(worktreeRaw);
797
+ const mainEntry = registered.find(entry => !entry.bare && samePath(entry.root, mainRoot));
798
+ if (!mainEntry) return null;
799
+ try {
800
+ const mainTop = canonical(git(mainRoot, ['rev-parse', '--show-toplevel']).trim());
801
+ const mainGitDir = canonical(path.resolve(mainRoot, git(mainRoot, ['rev-parse', '--git-dir']).trim()));
802
+ const mainCommonDir = canonical(path.resolve(mainRoot, git(mainRoot, ['rev-parse', '--git-common-dir']).trim()));
803
+ if (!samePath(mainTop, mainRoot) || !samePath(mainGitDir, commonDir) || !samePath(mainCommonDir, commonDir)) {
804
+ return null;
805
+ }
806
+ } catch (_) {
807
+ return null;
808
+ }
809
+ return mainRoot;
810
+ }
811
+
812
+ function inspectMemorySlug(targetRoot, home) {
813
+ const slugDir = path.join(home, '.claude', 'projects', path.resolve(targetRoot).replace(/[^a-z0-9]/gi, '-'));
316
814
  const directory = path.join(slugDir, 'memory');
317
815
  const files = flatMarkdown(directory);
318
816
  let reason = fs.existsSync(directory) ? 'hinted memory directory contains no Markdown files' : 'hinted memory directory is missing';
319
- const marker = path.join(slugDir, 'MEMORY.md');
320
- let verified = fs.existsSync(marker);
321
- let verificationRef = verified ? marker : undefined;
817
+ const currentMarker = path.join(directory, 'MEMORY.md');
818
+ const legacyMarker = path.join(slugDir, 'MEMORY.md');
819
+ const marker = isRegularFile(currentMarker) ? currentMarker : isRegularFile(legacyMarker) ? legacyMarker : null;
820
+ let verified = Boolean(marker);
821
+ let verificationRef = marker || undefined;
322
822
  if (verified) reason = 'automatic memory marker found';
323
823
  else if (files.length) {
324
824
  for (const file of files) {
325
825
  const text = safeRead(file) || '';
326
- if (text.includes(path.basename(root)) || text.includes(root)) {
826
+ if (text.includes(path.basename(targetRoot)) || text.includes(targetRoot)) {
327
827
  verified = true;
328
828
  verificationRef = file;
329
829
  reason = 'a memory file names the target repository';
@@ -335,6 +835,18 @@ function autoMemory(root, home) {
335
835
  return { directory, files, verified, reason, verificationRef };
336
836
  }
337
837
 
838
+ function autoMemory(root, home) {
839
+ const primary = inspectMemorySlug(root, home);
840
+ if (primary.verified) return primary;
841
+ const mainRoot = mainWorktreeRoot(root);
842
+ if (!mainRoot) return primary;
843
+ const fallback = inspectMemorySlug(mainRoot, home);
844
+ if (fallback.verified || (!primary.files.length && fallback.files.length)) {
845
+ return fallback;
846
+ }
847
+ return primary;
848
+ }
849
+
338
850
  function sourceStatus(type, origin, status, details = {}) {
339
851
  return { type, origin, status, ...details };
340
852
  }
@@ -411,13 +923,14 @@ function collectSources(options, root, home, files, historyCandidates) {
411
923
  return { sources, candidates };
412
924
  }
413
925
 
926
+ const trackedMemoryFiles = trackedRegularFiles(root);
414
927
  const auto = autoMemory(root, home);
415
928
  sources.push(sourceStatus('memory', 'auto', auto.files.length ? (auto.verified ? 'used' : 'unverified') : 'missing', {
416
929
  verified: auto.verified, reason: auto.reason,
417
930
  ref: localSourceId(auto.directory),
418
931
  ...(auto.verificationRef ? { verificationRef: localSourceId(auto.verificationRef) } : {})
419
932
  }));
420
- if (auto.verified) candidates.push(...candidatesFromFiles(auto.files, 'memory', root, home, knownFiles));
933
+ if (auto.verified) candidates.push(...candidatesFromFiles(auto.files, 'memory', root, home, trackedMemoryFiles));
421
934
 
422
935
  if (options.memory.length) {
423
936
  for (const input of options.memory) {
@@ -426,7 +939,7 @@ function collectSources(options, root, home, files, historyCandidates) {
426
939
  ref: localSourceId(input),
427
940
  ...(selected.length ? {} : { reason: 'no readable files at the selected path' })
428
941
  }));
429
- candidates.push(...candidatesFromFiles(selected, 'memory', root, home, knownFiles));
942
+ candidates.push(...candidatesFromFiles(selected, 'memory', root, home, trackedMemoryFiles));
430
943
  }
431
944
  } else {
432
945
  sources.push(sourceStatus('memory', 'explicit', 'missing', { reason: 'no --memory path provided' }));
@@ -4,7 +4,7 @@ description: "Route software/project work through Harness: classify tier/topolog
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.55.4
7
+ version: 1.2.2
8
8
  ---
9
9
 
10
10
  # Harness Everything