@bonesofspring/ai-rules 0.2.38 → 0.2.39

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 (110) hide show
  1. package/CHANGELOG.md +249 -6
  2. package/package.json +1 -1
  3. package/presets/_shared/ai-local/scripts/derive-gate-signals.mjs +4 -6
  4. package/presets/_shared/ai-local/scripts/efficacy-oracle.mjs +5 -0
  5. package/presets/_shared/ai-local/scripts/lock.mjs +101 -73
  6. package/presets/_shared/ai-local/scripts/rule-improver.mjs +1 -1
  7. package/presets/_shared/ai-local/scripts/run.mjs +13 -4
  8. package/presets/_shared/ai-local/scripts/signals.mjs +38 -8
  9. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +4 -5
  10. package/presets/_shared/hooks/check-preset-update.mjs +1 -1
  11. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +4 -5
  12. package/presets/claude/android-kotlin/hooks/check-preset-update.mjs +1 -1
  13. package/presets/claude/go/hooks/chain-team-phases.sh +4 -5
  14. package/presets/claude/go/hooks/check-preset-update.mjs +1 -1
  15. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +4 -5
  16. package/presets/claude/ios-swift/hooks/check-preset-update.mjs +1 -1
  17. package/presets/claude/java/hooks/chain-team-phases.sh +4 -5
  18. package/presets/claude/java/hooks/check-preset-update.mjs +1 -1
  19. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +4 -5
  20. package/presets/claude/mcp-ts/hooks/check-preset-update.mjs +1 -1
  21. package/presets/claude/next/hooks/chain-team-phases.sh +4 -5
  22. package/presets/claude/next/hooks/check-preset-update.mjs +1 -1
  23. package/presets/claude/nuxt/hooks/chain-team-phases.sh +4 -5
  24. package/presets/claude/nuxt/hooks/check-preset-update.mjs +1 -1
  25. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +4 -5
  26. package/presets/claude/php-hexagonal/hooks/check-preset-update.mjs +1 -1
  27. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +4 -5
  28. package/presets/claude/php-laravel/hooks/check-preset-update.mjs +1 -1
  29. package/presets/claude/svelte/hooks/chain-team-phases.sh +4 -5
  30. package/presets/claude/svelte/hooks/check-preset-update.mjs +1 -1
  31. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +4 -5
  32. package/presets/cursor/android-kotlin/hooks/check-preset-update.mjs +1 -1
  33. package/presets/cursor/go/hooks/chain-team-phases.sh +4 -5
  34. package/presets/cursor/go/hooks/check-preset-update.mjs +1 -1
  35. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +4 -5
  36. package/presets/cursor/ios-swift/hooks/check-preset-update.mjs +1 -1
  37. package/presets/cursor/java/hooks/chain-team-phases.sh +4 -5
  38. package/presets/cursor/java/hooks/check-preset-update.mjs +1 -1
  39. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +4 -5
  40. package/presets/cursor/mcp-ts/hooks/check-preset-update.mjs +1 -1
  41. package/presets/cursor/next/hooks/chain-team-phases.sh +4 -5
  42. package/presets/cursor/next/hooks/check-preset-update.mjs +1 -1
  43. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +4 -5
  44. package/presets/cursor/nuxt/hooks/check-preset-update.mjs +1 -1
  45. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +4 -5
  46. package/presets/cursor/php-hexagonal/hooks/check-preset-update.mjs +1 -1
  47. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +4 -5
  48. package/presets/cursor/php-laravel/hooks/check-preset-update.mjs +1 -1
  49. package/presets/cursor/svelte/hooks/chain-team-phases.sh +4 -5
  50. package/presets/cursor/svelte/hooks/check-preset-update.mjs +1 -1
  51. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  52. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +4 -5
  53. package/presets/mavis/android-kotlin/hooks/check-preset-update.mjs +1 -1
  54. package/presets/mavis/go/adapter-map.json +1 -1
  55. package/presets/mavis/go/hooks/chain-team-phases.sh +4 -5
  56. package/presets/mavis/go/hooks/check-preset-update.mjs +1 -1
  57. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  58. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +4 -5
  59. package/presets/mavis/ios-swift/hooks/check-preset-update.mjs +1 -1
  60. package/presets/mavis/java/adapter-map.json +1 -1
  61. package/presets/mavis/java/hooks/chain-team-phases.sh +4 -5
  62. package/presets/mavis/java/hooks/check-preset-update.mjs +1 -1
  63. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  64. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +4 -5
  65. package/presets/mavis/mcp-ts/hooks/check-preset-update.mjs +1 -1
  66. package/presets/mavis/next/adapter-map.json +1 -1
  67. package/presets/mavis/next/hooks/chain-team-phases.sh +4 -5
  68. package/presets/mavis/next/hooks/check-preset-update.mjs +1 -1
  69. package/presets/mavis/nuxt/adapter-map.json +1 -1
  70. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +4 -5
  71. package/presets/mavis/nuxt/hooks/check-preset-update.mjs +1 -1
  72. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  73. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +4 -5
  74. package/presets/mavis/php-hexagonal/hooks/check-preset-update.mjs +1 -1
  75. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  76. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +4 -5
  77. package/presets/mavis/php-laravel/hooks/check-preset-update.mjs +1 -1
  78. package/presets/mavis/svelte/adapter-map.json +1 -1
  79. package/presets/mavis/svelte/hooks/chain-team-phases.sh +4 -5
  80. package/presets/mavis/svelte/hooks/check-preset-update.mjs +1 -1
  81. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  82. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +4 -5
  83. package/presets/opencode/android-kotlin/hooks/check-preset-update.mjs +1 -1
  84. package/presets/opencode/go/adapter-map.json +1 -1
  85. package/presets/opencode/go/hooks/chain-team-phases.sh +4 -5
  86. package/presets/opencode/go/hooks/check-preset-update.mjs +1 -1
  87. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  88. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +4 -5
  89. package/presets/opencode/ios-swift/hooks/check-preset-update.mjs +1 -1
  90. package/presets/opencode/java/adapter-map.json +1 -1
  91. package/presets/opencode/java/hooks/chain-team-phases.sh +4 -5
  92. package/presets/opencode/java/hooks/check-preset-update.mjs +1 -1
  93. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  94. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +4 -5
  95. package/presets/opencode/mcp-ts/hooks/check-preset-update.mjs +1 -1
  96. package/presets/opencode/next/adapter-map.json +1 -1
  97. package/presets/opencode/next/hooks/chain-team-phases.sh +4 -5
  98. package/presets/opencode/next/hooks/check-preset-update.mjs +1 -1
  99. package/presets/opencode/nuxt/adapter-map.json +1 -1
  100. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +4 -5
  101. package/presets/opencode/nuxt/hooks/check-preset-update.mjs +1 -1
  102. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  103. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +4 -5
  104. package/presets/opencode/php-hexagonal/hooks/check-preset-update.mjs +1 -1
  105. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  106. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +4 -5
  107. package/presets/opencode/php-laravel/hooks/check-preset-update.mjs +1 -1
  108. package/presets/opencode/svelte/adapter-map.json +1 -1
  109. package/presets/opencode/svelte/hooks/chain-team-phases.sh +4 -5
  110. package/presets/opencode/svelte/hooks/check-preset-update.mjs +1 -1
package/CHANGELOG.md CHANGED
@@ -2,11 +2,6 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
- ### Presets report a newer package and name the latest version
6
-
7
- - Cursor `sessionStart` and Claude `SessionStart` run `hooks/check-preset-update.mjs`. Mavis and OpenCode run the same script on the first reply (`## Preset version` in root `AGENTS.md`).
8
- - When `packageVersion` in `<tool>/.ai-rules-install.json` is older than the npm latest for `@bonesofspring/ai-rules`, the agent tells the user the installed version, the latest version, and to run `/update`. A registry failure stays silent. The registry lookup is cached for 12 hours.
9
-
10
5
  ### `update` reinstalls the tools and presets already recorded
11
6
 
12
7
  - **CLI `update`.** Reads `platform` and `preset` from each existing `<tool>/.ai-rules-install.json` (`.cursor`, `.claude`, `.mavis`, `.opencode`) and re-runs `init` for those tools only. A tool without a manifest stays uninstalled. The recorded preset is kept; `--preset` and a tool name are rejected. The plan is validated before the first write, so a bad manifest does not partially update.
@@ -525,6 +520,254 @@ Cross-cutting preset packaging work (all six presets unless noted **next-only**)
525
520
 
526
521
  - **P2 optional (ios-swift):** Remaining polish: feature-delivery matrix enrichment, swift-conventions body cap. (`BUGBOT.md` shipped.)
527
522
 
523
+ ## 0.2.39
524
+
525
+ ### A `null` journal line no longer stops the self-learning loop
526
+
527
+ - `JSON.parse("null")` is valid JSON and returns `null`. Reading `.slug` / `.at` on it threw, and one such line aborted derivation, `run.mjs`, and the efficacy oracle.
528
+ - Those readers now require a non-null object that is not an array. A `null`, primitive, or array line is skipped and left in the file. `--status` counts it as malformed. Objects that are missing fields were already skipped.
529
+
530
+ ### `task_completed` is written only after `requireArtifacts` passes
531
+
532
+ - `chain-team-phases.sh` used to record `task_completed` and then call completion, which can still write `state: blocked` when `.ai.local/pipeline-gates.json` lists a receipt that is not completed. Metrics then showed a finished task that had failed the last check.
533
+ - The metric is written only on the success branch, after the receipt check, on every platform and stack. A missing receipt still blocks and writes no `task_completed`. A pipeline that completes because no step remains now records the metric too.
534
+
535
+ ### Derived signals are deduped inside the lock
536
+
537
+ - Two overlapping `run.mjs` runs could both derive the same `(slug, id, kind)` and both append it. The check now re-reads the journal under the lock before appending. The report's `appended` count includes only the row that was written.
538
+
539
+ ### The engine lock is `flock`, and the lock file stays
540
+
541
+ - Reclaiming a stale `.ai.local/scripts` lock by `unlink` could delete a lock a second process had just taken. Ownership is now a POSIX `flock` held by a short-lived `perl` helper (`Fcntl`, `Time::HiRes`). The helper drops the lock when its parent exits, including after a crash. The lock file is not removed: a file on disk does not mean the lock is held. `staleMs` is accepted and ignored.
542
+ - `perl` with those two modules is required. If it is missing, acquire fails with `lock helper unavailable: perl with Fcntl and Time::HiRes`.
543
+ - The metrics lock inside `chain-team-phases.sh` is unchanged (token file plus `unlink`).
544
+
545
+ ### Preset-update notice refreshes after one hour
546
+
547
+ - `hooks/check-preset-update.mjs` caches the npm `latest` lookup for 1 hour. `0.2.38` cached it for 12 hours.
548
+
549
+ ### Upgrade
550
+
551
+ - `npx @bonesofspring/ai-rules update` replaces the managed hooks, so the `task_completed` order and the one-hour cache land on re-init.
552
+ - `init` / `update` does not overwrite an existing `.ai.local/scripts/*.mjs`. The journal, dedup, and `flock` fixes ship in `run.mjs`, `signals.mjs`, `lock.mjs`, `rule-improver.mjs`, `derive-gate-signals.mjs`, and `efficacy-oracle.mjs`. If those files are still the copies from an older install, replace them with the package copies (a local edit is kept on purpose).
553
+
554
+ ## 0.2.38
555
+
556
+ ### Presets report a newer package and name the latest version
557
+
558
+ - Cursor `sessionStart` and Claude `SessionStart` run `hooks/check-preset-update.mjs`. Mavis and OpenCode run the same script on the first reply (`## Preset version` in root `AGENTS.md`).
559
+ - When `packageVersion` in `<tool>/.ai-rules-install.json` is older than the npm latest for `@bonesofspring/ai-rules`, the agent tells the user the installed version, the latest version, and to run `/update`. A registry failure stays silent. The registry lookup is cached for 12 hours.
560
+
561
+
562
+ ### Added
563
+
564
+ - Maintainer coverage: `scripts/test-preset-update-check.mjs` for the preset-update hook. (6023272d)
565
+
566
+ ## 0.2.37
567
+
568
+ ### Added
569
+
570
+ - Hook body parity and shared-core drift lineage fixture tests (`test-hook-body-parity-fixtures.mjs`, `test-shared-core-drift-lineage-fixtures.mjs`). (e9aea2d6)
571
+
572
+ ## 0.2.36
573
+
574
+ ### Changed
575
+
576
+ - OpenCode adapter generation and `scripts/lib/stack-platform-profiles.mjs`; extended `test-cli-mcp-merge.mjs`. (29897447)
577
+
578
+ ## 0.2.35
579
+
580
+ ### Added
581
+
582
+ - Generated-tree test fixtures (`test-generate-claude-fixtures.mjs`, `test-generated-drift-fixtures.mjs`, `test-generated-drift-claude-fixtures.mjs`). (26f438de)
583
+
584
+ ## 0.2.34
585
+
586
+ ### Added
587
+
588
+ - Chain hook coverage extensions (`test-chain-team-phases-coverage.mjs`, `test-parallel-plan-fixtures.mjs`). (057f6646)
589
+
590
+ ## 0.2.33
591
+
592
+ ### Added
593
+
594
+ - Preset contract fixture suites (`test-preset-language-policy-fixtures.mjs`, `test-preset-prompt-persistence-fixtures.mjs`, `test-preset-self-review-contract-fixtures.mjs`). (5d214e58)
595
+
596
+ ## 0.2.32
597
+
598
+ ### Changed
599
+
600
+ - Mavis/OpenCode adapter generators (`scripts/lib/generate-adapter-common.mjs`, `generate-mavis-adapter.mjs`, `generate-opencode-adapter.mjs`). (879ec753)
601
+
602
+ ## 0.2.30
603
+
604
+ ### Changed
605
+
606
+ - Refreshed Mavis/OpenCode CLI goldens (`scripts/fixtures/cli-golden/mavis/next.json`, `opencode/next.json`). (997c45f8)
607
+
608
+ ## 0.2.29
609
+
610
+ ### Added
611
+
612
+ - `scripts/sync-dogfood-claude.sh` for Claude dogfood sync from presets. (e22c5b7f)
613
+
614
+ ## 0.2.28
615
+
616
+ ### Added
617
+
618
+ - `scripts/sync-claude-settings.mjs`; additional `test-cli-mcp-merge.mjs` cases. (cc5ea6a9)
619
+
620
+ ## 0.2.27
621
+
622
+ ### Changed
623
+
624
+ - Large preset tree refresh under `packages/ai-rules/presets/**` (Mavis/OpenCode/Cursor twins). (f293ba6f)
625
+
626
+ ## 0.2.26
627
+
628
+ ### Changed
629
+
630
+ - Mass regeneration of Mavis/OpenCode install trees and related preset sources (`presets/mavis/**`, `presets/opencode/**`). (42bc7e13)
631
+
632
+ ## 0.2.25
633
+
634
+ ### Added
635
+
636
+ - **OpenCode** platform preset (`presets/opencode/**`) and `scripts/test-opencode-context-budget.mjs`. (1a05fffd)
637
+
638
+ ## 0.2.24
639
+
640
+ ### Changed
641
+
642
+ - Mavis preset review follow-up: `scripts/sync-dogfood-mavis.sh`, CLI golden tweaks. (df44f6f4)
643
+
644
+ ## 0.2.23
645
+
646
+ ### Added
647
+
648
+ - **Mavis** platform preset (`presets/mavis/**`) with `scripts/test-mavis-orchestration.mjs` and capability probes. (2f4880da)
649
+
650
+ ## 0.2.22
651
+
652
+ ### Added
653
+
654
+ - `scripts/test-task-router-intents-fixtures.mjs`; extended chain-hook coverage tests. (f7251cef)
655
+
656
+ ## 0.2.21
657
+
658
+ ### Added
659
+
660
+ - `scripts/test-chain-team-phases-coverage.mjs` for hook/agent handoff coverage. (73c2d788)
661
+
662
+ ## 0.2.20
663
+
664
+ ### Changed
665
+
666
+ - Preset cleanup and shared-core drift checks across stacks (`check-shared-core-drift.sh` updates). (0cebd54b)
667
+
668
+ ## 0.2.19
669
+
670
+ ### Added
671
+
672
+ - CLI MCP merge tests in `scripts/test-cli-mcp-merge.mjs`. (9208ab39)
673
+
674
+ ## 0.2.18
675
+
676
+ ### Added
677
+
678
+ - UX / mockup-review preset stems and routing updates (`feat: ux changes` diff under `presets/**/rules` and agents). (7e9a9040)
679
+
680
+ ## 0.2.17
681
+
682
+ ### Added
683
+
684
+ - Product specs checker `scripts/check-product-specs.sh` and related preset authoring assets. (97dd9696)
685
+
686
+ ## 0.2.16
687
+
688
+ ### Added
689
+
690
+ - **android-kotlin** installable preset (`presets/cursor/android-kotlin/**`, `presets/claude/android-kotlin/**`). (1271e4bb)
691
+
692
+ ## 0.2.15
693
+
694
+ ### Changed
695
+
696
+ - Preset English translation pass; `scripts/sync-shared-core-embeds.sh` and `check-preset-i18n` wiring. (260f29ca)
697
+
698
+ ## 0.2.14
699
+
700
+ ### Added
701
+
702
+ - **nuxt** and **svelte** installable presets (`presets/cursor/nuxt/**`, `presets/cursor/svelte/**`, Claude twins). (342200c1, 142e3650)
703
+
704
+ ## 0.2.13
705
+
706
+ ### Changed
707
+
708
+ - **php-laravel** preset follow-up; `scripts/aggregate-agent-task-metrics.mjs` and metrics hook tests extended. (f1da4526)
709
+
710
+ ## 0.2.12
711
+
712
+ ### Added
713
+
714
+ - **php-hexagonal** and **php-laravel** presets; `scripts/close-agent-task-human-gate.mjs` and `test-agent-task-metrics-hooks.mjs`. (d5057bfc)
715
+
716
+ ## 0.2.11
717
+
718
+ ### Added
719
+
720
+ - **mcp-ts** installable preset (`presets/cursor/mcp-ts/**`, `presets/claude/mcp-ts/**`). (175c8096)
721
+
722
+ ## 0.2.10
723
+
724
+ ### Changed
725
+
726
+ - Shared-core embed and token-budget script updates across stacks. (edb4f7eb)
727
+
728
+ ## 0.2.9
729
+
730
+ ### Added
731
+
732
+ - Requestable `react-next-anti-hallucination` rule (`presets/cursor/next/rules/react-next-anti-hallucination.mdc`). (ec27c49e)
733
+
734
+ ## 0.2.8
735
+
736
+ ### Changed
737
+
738
+ - Preset structure/leakage gate scripts (`check-preset-leakage.sh`, `check-preset-structure.sh`). (59157110)
739
+
740
+ ## 0.2.7
741
+
742
+ ### Added
743
+
744
+ - Opt-in rule eval harness `scripts/check-rule-eval.mjs`; team `conventions.md` template under cursor next. (03b4088b)
745
+
746
+ ## 0.2.6
747
+
748
+ ### Added
749
+
750
+ - Preset CI gates: `check-preset-twin-map.sh`, `check-preset-token-budget.sh`, `check-shared-core-drift.sh`, `sync-dogfood-cursor.sh`; `_shared/core/**` expansion. (5067c91e)
751
+
752
+ ## 0.2.5
753
+
754
+ ### Changed
755
+
756
+ - `task-router` agent and `agent-team-orchestrator` rule updates; team fixtures adjusted. (789e68a3)
757
+
758
+ ## 0.2.4
759
+
760
+ ### Added
761
+
762
+ - Cursor `next` MCP config (`presets/cursor/next/mcp.json`) and related orchestrator/team docs. (c4ad5eb4)
763
+
764
+ ## 0.2.3
765
+
766
+ ### Added
767
+
768
+ - **ios-swift** preset (`presets/cursor/ios-swift/**`, `presets/claude/ios-swift/**`). The same commit added the `## 0.2.2` changelog section; the file already existed. (87d0aed5)
769
+
770
+
528
771
  ## 0.2.2
529
772
 
530
773
  ### Breaking
@@ -561,4 +804,4 @@ Cross-cutting preset packaging work (all six presets unless noted **next-only**)
561
804
 
562
805
  ## 0.1.42
563
806
 
564
- Prior releases — see git history.
807
+ No `v0.1.*` git tags exist in this repository; 0.1.x release deltas are not recoverable from tags.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bonesofspring/ai-rules",
3
- "version": "0.2.38",
3
+ "version": "0.2.39",
4
4
  "description": "Presets of Cursor, Claude, Mavis, and OpenCode rules/commands for Revy Ross personal use",
5
5
  "license": "MIT",
6
6
  "author": "Revy Ross",
@@ -19,6 +19,7 @@ import fs from 'node:fs';
19
19
  import path from 'node:path';
20
20
 
21
21
  import { isDenied as defaultIsDenied } from './rule-improver.mjs';
22
+ import { isSignalRecord, signalIdentityKey } from './signals.mjs';
22
23
 
23
24
  export const DEFAULT_BASE_DIR = path.join(process.cwd(), '.ai.local');
24
25
 
@@ -33,10 +34,6 @@ export const DERIVED_TARGET = '.ai.local/conventions.md';
33
34
  export const DERIVED_CONFIDENCE = 80;
34
35
  export const DERIVED_AGENT_FALLBACK = 'gate-derivation';
35
36
 
36
- function dedupKey(slug, attemptId, kind) {
37
- return `${slug}\u0000${attemptId}\u0000${kind}`;
38
- }
39
-
40
37
  function humanize(stem) {
41
38
  return stem.replace(/-/g, ' ');
42
39
  }
@@ -57,8 +54,9 @@ function readExistingKeys(signalsPath) {
57
54
  if (trimmed === '') continue;
58
55
  let signal;
59
56
  try { signal = JSON.parse(trimmed); } catch { continue; }
57
+ if (!isSignalRecord(signal)) continue;
60
58
  if (typeof signal.slug === 'string' && typeof signal.id === 'string' && typeof signal.kind === 'string') {
61
- keys.add(dedupKey(signal.slug, signal.id, signal.kind));
59
+ keys.add(signalIdentityKey(signal));
62
60
  }
63
61
  }
64
62
  return keys;
@@ -145,7 +143,7 @@ export function deriveGateSignals({ baseDir = DEFAULT_BASE_DIR, isDenied = defau
145
143
  continue;
146
144
  }
147
145
 
148
- const key = dedupKey(slug, attemptId, kind);
146
+ const key = signalIdentityKey({ slug, id: attemptId, kind });
149
147
  if (existingKeys.has(key)) {
150
148
  skipped.push({ slug, attemptId, kind, reason: 'dedup: already captured' });
151
149
  continue;
@@ -25,6 +25,7 @@ import path from 'node:path';
25
25
  import { pathToFileURL } from 'node:url';
26
26
 
27
27
  import { isDenied } from './rule-improver.mjs';
28
+ import { isSignalRecord } from './signals.mjs';
28
29
 
29
30
  export const DEFAULT_BASE_DIR = path.join(process.cwd(), '.ai.local');
30
31
 
@@ -347,6 +348,10 @@ function readSignals(signalsPath) {
347
348
  errors.push({ line: index + 1, reason: error instanceof Error ? error.message : String(error) });
348
349
  return;
349
350
  }
351
+ if (!isSignalRecord(signal)) {
352
+ errors.push({ line: index + 1, reason: 'signal must be a JSON object' });
353
+ return;
354
+ }
350
355
  if (typeof signal.at !== 'string' || Number.isNaN(Date.parse(signal.at))) {
351
356
  errors.push({ line: index + 1, reason: '"at" must be an ISO timestamp' });
352
357
  return;
@@ -1,35 +1,56 @@
1
1
  /**
2
- * Shared advisory file lock with ownership token.
2
+ * Shared exclusive lock for the self-learning journal.
3
3
  *
4
- * The slug-1 review flagged a stale-reclaim race in the token-less lock
5
- * inherited from `waitForMetricsLock`: process A holds the lock longer than
6
- * STALE_LOCK_MS, process B reclaims it by mtime and acquires its own lock,
7
- * then A's `releaseLock` unlinks B's lock — opening a parallel-write window.
4
+ * Ownership is a POSIX `flock` held by a short-lived `perl` helper, not the
5
+ * presence of the lock file. The helper polls its parent pid and exits when
6
+ * that process dies, so a killed owner cannot leave the lock stuck, and the
7
+ * kernel drops the flock with the helper. The lock file is never unlinked:
8
+ * a delayed `unlink` of the path deletes a newer owner's file after
9
+ * `acquireLock` has already returned.
8
10
  *
9
- * This module closes it: every acquired lock writes an ownership token
10
- * (`pid:nonce`) into the lock file; release unlinks only if the file still
11
- * carries our token; stale reclaim happens only when the lock is stale AND
12
- * the recorded owner pid is no longer alive. Shared by `signals.mjs` and
13
- * `rule-improver.mjs` (Rule of Three: two consumers).
14
- *
15
- * Reclaim is `unlink` + re-`wx` (not a single CAS): the `wx` retry is the
16
- * atomic acquire — at most one contender wins; losers EEXIST and retry.
11
+ * `releaseLock` only drops a lock this process acquired. A token from another
12
+ * process is ignored.
17
13
  */
18
14
 
19
- import fs from 'node:fs';
15
+ import { spawn, spawnSync } from 'node:child_process';
20
16
  import crypto from 'node:crypto';
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
21
19
 
22
20
  export const DEFAULT_STALE_MS = 30000;
23
21
  export const DEFAULT_MAX_ATTEMPTS = 200;
24
22
  export const DEFAULT_BUSY_WAIT_MS = 10;
25
23
 
26
- function newToken() {
27
- return `${process.pid}:${crypto.randomBytes(8).toString('hex')}`;
24
+ // `$` is literal here: only `${` interpolates.
25
+ const FLOCK_HELPER = `
26
+ use Fcntl qw(:flock);
27
+ use Time::HiRes qw(usleep time);
28
+ my ($path, $ready, $timeout_ms) = @ARGV;
29
+ open my $fh, '>>', $path or exit 2;
30
+ my $deadline = time() + ($timeout_ms / 1000.0);
31
+ my $locked = 0;
32
+ while (1) {
33
+ if (flock($fh, LOCK_EX | LOCK_NB)) { $locked = 1; last; }
34
+ exit 1 if time() >= $deadline;
35
+ usleep(2000);
28
36
  }
37
+ exit 1 unless $locked;
38
+ open my $rf, '>', $ready or exit 2;
39
+ print $rf "1\\n";
40
+ close $rf;
41
+ my $parent = getppid();
42
+ while (getppid() == $parent) { usleep(20000); }
43
+ unlink $ready;
44
+ flock($fh, LOCK_UN);
45
+ close $fh;
46
+ `;
29
47
 
30
- function pidFromToken(token) {
31
- const match = /^(\d+):/.exec(token ?? '');
32
- return match ? Number(match[1]) : null;
48
+ const holders = new Map();
49
+ let perlReady = false;
50
+ let exitHooked = false;
51
+
52
+ function newToken() {
53
+ return `${process.pid}:${crypto.randomBytes(8).toString('hex')}`;
33
54
  }
34
55
 
35
56
  /**
@@ -45,74 +66,81 @@ export function isPidAlive(pid) {
45
66
  }
46
67
  }
47
68
 
48
- function readToken(lockPath) {
49
- try {
50
- const content = fs.readFileSync(lockPath, 'utf8').trim();
51
- return content.length > 0 ? content : null;
52
- } catch {
53
- return null;
69
+ const pauseView = new Int32Array(new SharedArrayBuffer(4));
70
+
71
+ function busyWait(ms) {
72
+ Atomics.wait(pauseView, 0, 0, ms);
73
+ }
74
+
75
+ function assertPerl() {
76
+ if (perlReady) return;
77
+ const probe = spawnSync('perl', ['-e', 'use Fcntl qw(:flock); use Time::HiRes qw(usleep time); exit 0'], {
78
+ stdio: 'ignore',
79
+ });
80
+ if (probe.error || probe.status !== 0) {
81
+ throw new Error('lock helper unavailable: perl with Fcntl and Time::HiRes');
54
82
  }
83
+ perlReady = true;
55
84
  }
56
85
 
57
- function busyWait(ms) {
58
- const until = Date.now() + ms;
59
- while (Date.now() < until) { /* busy-wait */ }
86
+ function ensureExitHook() {
87
+ if (exitHooked) return;
88
+ exitHooked = true;
89
+ process.on('exit', () => {
90
+ for (const holder of holders.values()) {
91
+ try { process.kill(holder.pid, 'SIGTERM'); } catch { /* already gone */ }
92
+ }
93
+ });
94
+ }
95
+
96
+ function stopHolder(holder) {
97
+ try { process.kill(holder.pid, 'SIGTERM'); } catch { /* already gone */ }
98
+ try { fs.unlinkSync(holder.ready); } catch { /* ready file already gone */ }
60
99
  }
61
100
 
62
101
  /**
63
- * Acquire the advisory lock at `lockPath`, returning the ownership token that
64
- * must be passed to `releaseLock`. Throws on lock timeout.
102
+ * Acquire the exclusive lock at `lockPath`, returning the token that must be
103
+ * passed to `releaseLock`. Throws on timeout. `staleMs` is accepted and
104
+ * ignored: a dead owner is recovered by the helper's parent-pid watch, not
105
+ * by deleting the lock file.
65
106
  */
66
107
  export function acquireLock(lockPath, options = {}) {
67
- const staleMs = options.staleMs ?? DEFAULT_STALE_MS;
68
- const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
69
- const busyWaitMs = options.busyWaitMs ?? DEFAULT_BUSY_WAIT_MS;
70
- const checkLive = options.isPidAlive ?? isPidAlive;
108
+ assertPerl();
109
+ const timeoutMs = options.timeoutMs
110
+ ?? (options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS) * (options.busyWaitMs ?? DEFAULT_BUSY_WAIT_MS);
111
+ const directory = path.dirname(lockPath);
112
+ if (!fs.existsSync(directory)) {
113
+ const error = new Error(`ENOENT: no such file or directory, open '${lockPath}'`);
114
+ error.code = 'ENOENT';
115
+ throw error;
116
+ }
71
117
  const token = newToken();
72
-
73
- for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
74
- let fd;
75
- try {
76
- fd = fs.openSync(lockPath, 'wx');
77
- } catch (error) {
78
- if (!error || error.code !== 'EEXIST') throw error;
79
- let stat = null;
80
- try { stat = fs.statSync(lockPath); } catch { /* lock vanished; retry */ }
81
- const stale = stat !== null && Date.now() - stat.mtimeMs > staleMs;
82
- if (stale) {
83
- const ownerPid = pidFromToken(readToken(lockPath));
84
- // Reclaim only when the recorded owner is provably gone. A live owner
85
- // holding the lock past staleMs is left alone — do not steal it.
86
- if (ownerPid === null || !checkLive(ownerPid)) {
87
- try { fs.unlinkSync(lockPath); } catch { /* already reclaimed */ }
88
- continue;
89
- }
90
- }
91
- busyWait(busyWaitMs);
92
- continue;
93
- }
94
- // Created exclusively — write the ownership token into the lock file.
95
- try {
96
- fs.writeSync(fd, token);
97
- try { fs.fsyncSync(fd); } catch {}
98
- } finally {
99
- try { fs.closeSync(fd); } catch {}
118
+ const ready = `${lockPath}.${token}.ready`;
119
+ ensureExitHook();
120
+ const child = spawn('perl', ['-e', FLOCK_HELPER, lockPath, ready, String(timeoutMs)], { stdio: 'ignore' });
121
+ child.unref();
122
+ child.on('error', () => {});
123
+ child.on('exit', () => {});
124
+ const deadline = Date.now() + timeoutMs + 500;
125
+ while (!fs.existsSync(ready)) {
126
+ if (!isPidAlive(child.pid) || Date.now() > deadline) {
127
+ stopHolder({ pid: child.pid, ready });
128
+ throw new Error('lock timeout');
100
129
  }
101
- // Re-read the path: a concurrent reclaim could have unlinked the still-empty
102
- // file after our `wx` won but before the token landed, leaving our fd
103
- // writing into an unlinked inode while a new owner holds the path. If the
104
- // file no longer carries our token, retry the acquire (S1).
105
- if (readToken(lockPath) !== token) continue;
106
- return token;
130
+ busyWait(2);
107
131
  }
108
- throw new Error('lock timeout');
132
+ holders.set(token, { pid: child.pid, ready });
133
+ return token;
109
134
  }
110
135
 
111
136
  /**
112
- * Release `lockPath` only if it still carries our `token`. If another
113
- * process reclaimed the lock after us, we must not unlink their file.
137
+ * Release the lock acquired as `token` in this process. A token this process
138
+ * does not hold is a no-op, so one process cannot drop another's lock.
114
139
  */
115
140
  export function releaseLock(lockPath, token) {
116
- if (readToken(lockPath) !== token) return;
117
- try { fs.unlinkSync(lockPath); } catch {}
141
+ void lockPath;
142
+ const holder = holders.get(token);
143
+ if (!holder) return;
144
+ holders.delete(token);
145
+ stopHolder(holder);
118
146
  }
@@ -6,7 +6,7 @@
6
6
  * `groupSignatures` from signals.mjs for the Rule-of-Three counts), re-derive
7
7
  * the rule text from the validated signature via a canonical template (never
8
8
  * from task/spec prose), validate the authoring envelope + denylist + two-band
9
- * autonomy, then apply or stage under the shared ownership-token lock.
9
+ * autonomy, then apply or stage under the shared exclusive lock.
10
10
  *
11
11
  * Writes are scoped to `.ai.local/**` only. The loop never edits this module
12
12
  * or its denylist (self-reference guard, §5.2).
@@ -26,7 +26,7 @@ import fs from 'node:fs';
26
26
  import path from 'node:path';
27
27
  import { pathToFileURL } from 'node:url';
28
28
 
29
- import { appendSignal, groupSignatures } from './signals.mjs';
29
+ import { appendSignal, groupSignatures, isSignalRecord } from './signals.mjs';
30
30
  import {
31
31
  MAX_ACTIVE_RULES,
32
32
  MAX_TOTAL_LINES,
@@ -110,8 +110,16 @@ export function runLoop({ baseDir = DEFAULT_BASE_DIR } = {}) {
110
110
  const appendErrors = [];
111
111
  for (const signal of derived.signals) {
112
112
  try {
113
- appendSignal(signal, { signalsPath });
114
- appended.push(signal);
113
+ const result = appendSignal(signal, { signalsPath, dedup: true });
114
+ if (result.appended) appended.push(signal);
115
+ else {
116
+ derived.skipped.push({
117
+ slug: signal.slug,
118
+ attemptId: signal.id,
119
+ kind: signal.kind,
120
+ reason: 'dedup: already captured',
121
+ });
122
+ }
115
123
  } catch (error) {
116
124
  appendErrors.push({ signature: signal.signature, reason: error instanceof Error ? error.message : String(error) });
117
125
  }
@@ -148,6 +156,7 @@ function lastCaptureBySignature({ signalsPath }) {
148
156
  if (trimmed === '') continue;
149
157
  let signal;
150
158
  try { signal = JSON.parse(trimmed); } catch { continue; }
159
+ if (!isSignalRecord(signal)) continue;
151
160
  if (typeof signal.signature !== 'string' || typeof signal.at !== 'string') continue;
152
161
  if (signal.status === 'rejected' || signal.status === 'rolled_back') continue;
153
162
  const previous = latest.get(signal.signature);
@@ -233,7 +242,7 @@ export function captureHealth({ baseDir = DEFAULT_BASE_DIR, window = CAPTURE_WIN
233
242
  if (trimmed === '') continue;
234
243
  try {
235
244
  const signal = JSON.parse(trimmed);
236
- if (typeof signal.slug === 'string') capturedSlugs.add(signal.slug);
245
+ if (isSignalRecord(signal) && typeof signal.slug === 'string') capturedSlugs.add(signal.slug);
237
246
  } catch { /* a malformed line is reported by --status, not counted here */ }
238
247
  }
239
248
  }