agent-rulebook 0.1.1 → 0.1.3

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 (72) hide show
  1. package/README.md +125 -13
  2. package/dist/commands/output.js +2 -0
  3. package/dist/commands/output.js.map +1 -1
  4. package/dist/commands/rule.d.ts +23 -0
  5. package/dist/commands/rule.js +158 -0
  6. package/dist/commands/rule.js.map +1 -0
  7. package/dist/commands/sync.d.ts +19 -0
  8. package/dist/commands/sync.js +262 -0
  9. package/dist/commands/sync.js.map +1 -0
  10. package/dist/core/compatibility-matcher.d.ts +1 -1
  11. package/dist/core/compatibility-matcher.js.map +1 -1
  12. package/dist/core/git.d.ts +7 -0
  13. package/dist/core/git.js +16 -0
  14. package/dist/core/git.js.map +1 -0
  15. package/dist/core/index.d.ts +8 -2
  16. package/dist/core/index.js +4 -1
  17. package/dist/core/index.js.map +1 -1
  18. package/dist/core/ranker.js +23 -2
  19. package/dist/core/ranker.js.map +1 -1
  20. package/dist/core/remote-guardrail.d.ts +7 -0
  21. package/dist/core/remote-guardrail.js +18 -0
  22. package/dist/core/remote-guardrail.js.map +1 -0
  23. package/dist/core/rule-schema.d.ts +36 -2
  24. package/dist/core/rule-schema.js +20 -2
  25. package/dist/core/rule-schema.js.map +1 -1
  26. package/dist/core/search-types.d.ts +1 -0
  27. package/dist/core/semantic-checksum.d.ts +6 -0
  28. package/dist/core/semantic-checksum.js +34 -0
  29. package/dist/core/semantic-checksum.js.map +1 -0
  30. package/dist/index.d.ts +3 -2
  31. package/dist/index.js +2 -1
  32. package/dist/index.js.map +1 -1
  33. package/dist/mcp/lesson-capture.js +0 -2
  34. package/dist/mcp/lesson-capture.js.map +1 -1
  35. package/dist/mcp/server.js +2 -1
  36. package/dist/mcp/server.js.map +1 -1
  37. package/dist/migration/applier.js +102 -17
  38. package/dist/migration/applier.js.map +1 -1
  39. package/dist/migration/manifest.d.ts +1 -0
  40. package/dist/migration/manifest.js +2 -0
  41. package/dist/migration/manifest.js.map +1 -1
  42. package/dist/migration/migration-report.d.ts +4 -0
  43. package/dist/migration/migration-report.js +4 -0
  44. package/dist/migration/migration-report.js.map +1 -1
  45. package/dist/migration/scanner.js +2 -0
  46. package/dist/migration/scanner.js.map +1 -1
  47. package/dist/migration/verifier.js +17 -21
  48. package/dist/migration/verifier.js.map +1 -1
  49. package/dist/program.js +6 -1
  50. package/dist/program.js.map +1 -1
  51. package/dist/storage/atomic-file.d.ts +1 -0
  52. package/dist/storage/atomic-file.js +43 -0
  53. package/dist/storage/atomic-file.js.map +1 -0
  54. package/dist/storage/index-check.d.ts +2 -0
  55. package/dist/storage/index-check.js +34 -12
  56. package/dist/storage/index-check.js.map +1 -1
  57. package/dist/storage/index.d.ts +1 -0
  58. package/dist/storage/index.js +1 -0
  59. package/dist/storage/index.js.map +1 -1
  60. package/dist/storage/indexer.js +18 -5
  61. package/dist/storage/indexer.js.map +1 -1
  62. package/dist/storage/migrations.d.ts +1 -1
  63. package/dist/storage/migrations.js +17 -1
  64. package/dist/storage/migrations.js.map +1 -1
  65. package/dist/storage/rulebook-home.js +3 -0
  66. package/dist/storage/rulebook-home.js.map +1 -1
  67. package/dist/storage/search-service.js +1 -0
  68. package/dist/storage/search-service.js.map +1 -1
  69. package/dist/version.d.ts +4 -0
  70. package/dist/version.js +33 -0
  71. package/dist/version.js.map +1 -0
  72. package/package.json +2 -1
package/README.md CHANGED
@@ -4,11 +4,12 @@ TypeScript CLI and MCP foundation for managing reusable agent rules.
4
4
 
5
5
  ## Requirements
6
6
 
7
- The `0.1.1` release supports Node.js 20 and 22 through 26. Node.js 21
7
+ The packaged `0.1.3` artifact supports Node.js 20 and 22 through 26. Node.js 21
8
8
  is excluded because the pinned `better-sqlite3@12.11.1` native runtime does not
9
- declare support for it. The registry artifact matrix currently covers Node 26
10
- on Darwin arm64. Windows x64 remains a deferred gate before implementation
11
- completion or a Windows/cross-platform support claim.
9
+ declare support for it. The first supported platform is Darwin arm64, where the
10
+ local tarball matrix covers Node.js 20 and 22 through 26. Windows x64 is currently
11
+ unverified and unsupported; its native acceptance matrix is required before any
12
+ Windows or cross-platform support claim, but it does not block the Darwin-only rollout.
12
13
 
13
14
  Agent Rulebook keeps rule YAML and its rebuildable SQLite index outside the npm
14
15
  package in `~/.agent-rulebook` by default. Reinstalling the package or clearing
@@ -19,17 +20,129 @@ the npm cache must not remove that data.
19
20
  Run the published immutable version without a global install:
20
21
 
21
22
  ```bash
22
- npx -y agent-rulebook@0.1.1 --help
23
- npx -y agent-rulebook@0.1.1 mcp
23
+ npx -y agent-rulebook@0.1.3 --help
24
+ npx -y agent-rulebook@0.1.3 mcp
24
25
  ```
25
26
 
26
- `agent-rulebook@0.1.1` is the current immutable patch release. Production
27
- configuration should pin the exact version.
27
+ `agent-rulebook@0.1.3` is an immutable package version. Production
28
+ configuration should pin this exact version. Registry tags such as `latest` are
29
+ mutable and are not asserted by this artifact.
28
30
 
29
31
  ## Documentation
30
32
 
31
33
  - [Codex adapter setup](docs/adapters/codex.md)
32
34
 
35
+ ## Private YAML sync
36
+
37
+ Initialize `~/.agent-rulebook` as a Git repository whose tracked files are limited
38
+ to `rules/**/*.yaml`, `.gitignore`, and a safe `config.yaml` or
39
+ `config.example.yaml`. SQLite/WAL/SHM files, locks, logs, reports, and temporary
40
+ files must remain untracked. Setup documentation stays in this product repository,
41
+ not in the private data remote. If any local artifact or other non-allowlisted
42
+ file is tracked, `sync push` fails with a remediation path.
43
+
44
+ ### First machine and an empty private remote
45
+
46
+ Create an empty private repository with the Git hosting provider. Do not add a
47
+ server-generated README, license, or `.gitignore`. Then initialize and commit the
48
+ local Rulebook data:
49
+
50
+ ```bash
51
+ agent-rulebook init
52
+ git -C ~/.agent-rulebook init -b main
53
+ git -C ~/.agent-rulebook remote add origin <private-remote-url>
54
+ git -C ~/.agent-rulebook add .gitignore config.yaml
55
+ git -C ~/.agent-rulebook commit -m "Initialize private Agent Rulebook data"
56
+ ```
57
+
58
+ Verify the repository visibility with the hosting provider. Only after it is
59
+ confirmed private, record that evidence in local Git config. This marker is local
60
+ and must be configured independently on every machine:
61
+
62
+ ```bash
63
+ git -C ~/.agent-rulebook config remote.origin.agentRulebookPrivacy private
64
+ agent-rulebook sync push # preview remote URL and changed files
65
+ agent-rulebook sync push --yes # execute exactly the reviewed push
66
+ ```
67
+
68
+ The privacy marker is not inferred from the URL. A missing/unknown marker or a
69
+ `public` marker blocks push. Before invoking Git, the command also requires a
70
+ clean, conflict-free worktree and preflights every changed rule through schema
71
+ validation and secret detection. `sync pull` uses fast-forward-only Git and then
72
+ checks/rebuilds the local SQLite projection from canonical YAML.
73
+
74
+ Actual private-remote writes remain user-approved operations. Inspect the target
75
+ and commits with `git remote -v` and `git log --oneline @{upstream}..HEAD` before
76
+ the first real push.
77
+
78
+ ### Additional machine
79
+
80
+ On a new machine, clone first so `agent-rulebook init` does not create a nonempty
81
+ destination before Git:
82
+
83
+ ```bash
84
+ git clone <private-remote-url> ~/.agent-rulebook
85
+ agent-rulebook init
86
+ git -C ~/.agent-rulebook config remote.origin.agentRulebookPrivacy private
87
+ agent-rulebook sync pull
88
+ agent-rulebook index check
89
+ ```
90
+
91
+ `sync pull` is fast-forward-only. It validates the pulled rule sources and checks
92
+ the local index, rebuilding SQLite when the source count, semantic checksum, or
93
+ schema version differs. The SQLite database is created separately on every
94
+ machine and is never pulled from Git.
95
+
96
+ An intentionally empty data remote is a valid initial state. In that case,
97
+ `index check --json` should report `status: ok`, `sourceCount: 0`, and
98
+ `indexedCount: 0`; search returns no results until the first active canonical rule
99
+ is committed. Do not seed a new private remote from temporary test homes or
100
+ fixtures—wait for a real rule or migrate a reviewed permanent source.
101
+
102
+ ### Normal workflow
103
+
104
+ ```bash
105
+ agent-rulebook sync pull
106
+ # Add, verify, deprecate, or supersede rules locally.
107
+ git -C ~/.agent-rulebook add rules
108
+ git -C ~/.agent-rulebook commit -m "Update Agent Rulebook rules"
109
+ agent-rulebook sync push
110
+ agent-rulebook sync push --yes
111
+ ```
112
+
113
+ If `sync push` reports a dirty worktree, commit the reviewed canonical YAML change
114
+ first. If it reports a conflict, resolve every listed YAML field and rebuild the
115
+ index before retrying.
116
+
117
+ ## Lifecycle and recovery
118
+
119
+ Lifecycle changes preview by default; add `--yes` after reviewing the target:
120
+
121
+ ```bash
122
+ agent-rulebook rule verify <draft-id> --evidence <test-or-review-reference>
123
+ agent-rulebook rule deprecate <active-id>
124
+ agent-rulebook rule supersede <active-id> --replacement <active-replacement-id>
125
+ ```
126
+
127
+ Verification requires explicit evidence and known compatibility. Superseding
128
+ requires an existing active replacement and rejects replacement cycles. Applied
129
+ changes atomically replace one YAML source and rebuild SQLite, so default CLI/MCP
130
+ search immediately reflects the lifecycle state.
131
+
132
+ Use these local-first recovery paths:
133
+
134
+ ```bash
135
+ agent-rulebook index check
136
+ agent-rulebook index rebuild
137
+ git -C ~/.agent-rulebook status
138
+ ```
139
+
140
+ - For a corrupt, outdated, or checksum-mismatched index, rebuild from YAML.
141
+ - For Git conflicts, resolve every listed YAML file and validate it before
142
+ rebuilding or pushing; the tool never auto-merges rule conflicts.
143
+ - For a bad synced commit, create a normal `git revert <commit>` rollback, then
144
+ pull and rebuild. Do not restore or synchronize a SQLite file.
145
+
33
146
  ## Development
34
147
 
35
148
  ```bash
@@ -59,9 +172,8 @@ platform, and architecture so unsupported native combinations can be reported.
59
172
 
60
173
  ## Release status
61
174
 
62
- The release version is `0.1.1`, the package is explicitly `UNLICENSED`, and
175
+ The packaged release version is `0.1.3`, the package is explicitly `UNLICENSED`, and
63
176
  no public repository, homepage, or issue tracker is currently advertised because
64
- the source remote is not publicly accessible. The unscoped package name returned
65
- `E404` on 2026-08-19, but availability must be checked again immediately before
66
- publish; use an owned npm scope if it has been claimed. No publish or dist-tag
67
- operation is performed by the local verification scripts.
177
+ the source remote is not publicly accessible. Package availability and mutable
178
+ registry tags must be checked again immediately before publish. No publish or
179
+ dist-tag operation is performed by the local verification scripts.
@@ -26,6 +26,8 @@ export function writeIndexCheckText(result) {
26
26
  process.stdout.write(`status\t${result.status}\n`);
27
27
  process.stdout.write(`sourceCount\t${result.sourceCount}\n`);
28
28
  process.stdout.write(`indexedCount\t${result.indexedCount}\n`);
29
+ process.stdout.write(`sourceChecksum\t${result.sourceChecksum}\n`);
30
+ process.stdout.write(`indexedChecksum\t${result.indexedChecksum ?? 'unavailable'}\n`);
29
31
  process.stdout.write(`indexPath\t${result.indexPath}\n`);
30
32
  if (result.runtime !== undefined) {
31
33
  process.stdout.write(`userVersion\t${result.runtime.userVersion}\n`);
@@ -1 +1 @@
1
- {"version":3,"file":"output.js","sourceRoot":"","sources":["../../src/commands/output.ts"],"names":[],"mappings":"AAGA,MAAM,UAAU,SAAS,CAAC,KAAc;IACtC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,QAAwB;IACtD,IAAI,QAAQ,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAClC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,QAAQ,CAAC,IAAI,IAAI,YAAY,IAAI,CAAC,CAAC;QAC3D,OAAO;IACT,CAAC;IAED,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,wCAAwC,CAAC,CAAC;IAC/D,KAAK,MAAM,MAAM,IAAI,QAAQ,CAAC,OAAO,EAAE,CAAC;QACtC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC,CAAC;IACnD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,MAAkC;IACtE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,cAAc,MAAM,CAAC,SAAS,IAAI,CAAC,CAAC;IACzD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,YAAY,MAAM,CAAC,YAAY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,IAAI,CAAC,CAAC;QACrE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,wBAAwB,MAAM,CAAC,OAAO,CAAC,mBAAmB,IAAI,CAAC,CAAC;QACrF,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,kBAAkB,MAAM,CAAC,OAAO,CAAC,aAAa,IAAI,CAAC,CAAC;QACzE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,cAAc,MAAM,CAAC,OAAO,CAAC,SAAS,IAAI,CAAC,CAAC;IACnE,CAAC;IAED,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAC9B,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,SAAS,MAAM,CAAC,IAAI,IAAI,CAAC,CAAC;IACjD,CAAC;AACH,CAAC;AAED,SAAS,kBAAkB,CAAC,MAAoB;IAC9C,OAAO;QACL,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,MAAM,KAAK,MAAM,CAAC,UAAU,KAAK,MAAM,CAAC,EAAE,KAAK,MAAM,CAAC,KAAK,EAAE;QACnG,YAAY,MAAM,CAAC,OAAO,EAAE;QAC5B,QAAQ,MAAM,CAAC,GAAG,EAAE;QACpB,SAAS,MAAM,CAAC,IAAI,EAAE;QACtB,EAAE;KACH,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACf,CAAC"}
@@ -0,0 +1,23 @@
1
+ import type { Command } from 'commander';
2
+ type LifecycleAction = 'deprecate' | 'supersede' | 'verify';
3
+ type LifecycleIssue = {
4
+ code: string;
5
+ message: string;
6
+ ruleId?: string;
7
+ };
8
+ type LifecycleOptions = {
9
+ evidence?: string;
10
+ replacement?: string;
11
+ yes?: boolean;
12
+ json?: boolean;
13
+ };
14
+ type LifecycleResult = {
15
+ status: 'blocked' | 'preview' | 'updated';
16
+ action: LifecycleAction;
17
+ ruleId: string;
18
+ replacement?: string;
19
+ issues: LifecycleIssue[];
20
+ };
21
+ export declare function registerRuleCommand(program: Command): Command;
22
+ export declare function changeRuleLifecycle(home: string, action: LifecycleAction, ruleId: string, options: LifecycleOptions): Promise<LifecycleResult>;
23
+ export {};
@@ -0,0 +1,158 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { stringify } from 'yaml';
4
+ import { parseRuleYaml, resolveRulebookHome, RuleSchema, } from '../core/index.js';
5
+ import { discoverRuleFiles, rebuildRulebookIndex, replaceFileAtomically, } from '../storage/index.js';
6
+ import { writeJson } from './output.js';
7
+ export function registerRuleCommand(program) {
8
+ const rule = program.command('rule').description('Manage rule lifecycle state');
9
+ rule
10
+ .command('verify')
11
+ .argument('<id>', 'Draft rule id')
12
+ .requiredOption('--evidence <evidence>', 'Verification evidence')
13
+ .option('--yes', 'Apply the previewed lifecycle change')
14
+ .option('--json', 'Print JSON output')
15
+ .action(async (id, options) => {
16
+ emitLifecycle(await changeRuleLifecycle(resolveRulebookHome(), 'verify', id, options), options);
17
+ });
18
+ rule
19
+ .command('deprecate')
20
+ .argument('<id>', 'Active rule id')
21
+ .option('--yes', 'Apply the previewed lifecycle change')
22
+ .option('--json', 'Print JSON output')
23
+ .action(async (id, options) => {
24
+ emitLifecycle(await changeRuleLifecycle(resolveRulebookHome(), 'deprecate', id, options), options);
25
+ });
26
+ rule
27
+ .command('supersede')
28
+ .argument('<id>', 'Active rule id')
29
+ .requiredOption('--replacement <id>', 'Replacement rule id')
30
+ .option('--yes', 'Apply the previewed lifecycle change')
31
+ .option('--json', 'Print JSON output')
32
+ .action(async (id, options) => {
33
+ emitLifecycle(await changeRuleLifecycle(resolveRulebookHome(), 'supersede', id, options), options);
34
+ });
35
+ return program;
36
+ }
37
+ export async function changeRuleLifecycle(home, action, ruleId, options) {
38
+ const loaded = await loadRuleSources(home);
39
+ if (loaded.issues.length > 0) {
40
+ return { status: 'blocked', action, ruleId, issues: loaded.issues };
41
+ }
42
+ const matches = loaded.rules.filter((item) => item.rule.id === ruleId);
43
+ if (matches.length !== 1) {
44
+ return {
45
+ status: 'blocked', action, ruleId,
46
+ issues: [{ code: matches.length === 0 ? 'rule_missing' : 'duplicate_rule_id', message: `Expected exactly one source for ${ruleId}.`, ruleId }],
47
+ };
48
+ }
49
+ const target = matches[0];
50
+ const issues = validateTransition(action, target.rule, loaded.rules, options);
51
+ if (issues.length > 0) {
52
+ return { status: 'blocked', action, ruleId, replacement: options.replacement, issues };
53
+ }
54
+ if (options.yes !== true) {
55
+ return { status: 'preview', action, ruleId, replacement: options.replacement, issues: [] };
56
+ }
57
+ const now = new Date().toISOString().slice(0, 10);
58
+ const candidate = {
59
+ ...target.rule,
60
+ status: action === 'verify' ? 'active' : action === 'deprecate' ? 'deprecated' : 'superseded',
61
+ updated_at: now,
62
+ ...(action === 'verify' ? { verified_at: now } : {}),
63
+ superseded_by: action === 'supersede' ? options.replacement : null,
64
+ };
65
+ delete candidate.legacy;
66
+ const normalized = RuleSchema.safeParse(candidate);
67
+ if (!normalized.success) {
68
+ return { status: 'blocked', action, ruleId, issues: [{ code: 'invalid_rule', message: normalized.error.message, ruleId }] };
69
+ }
70
+ const yaml = stringify(normalized.data, { lineWidth: 0 });
71
+ await replaceFileAtomically(target.path, yaml);
72
+ try {
73
+ await rebuildRulebookIndex({ home });
74
+ }
75
+ catch (error) {
76
+ await replaceFileAtomically(target.path, target.source);
77
+ await rebuildRulebookIndex({ home });
78
+ throw error;
79
+ }
80
+ return { status: 'updated', action, ruleId, replacement: options.replacement, issues: [] };
81
+ }
82
+ function validateTransition(action, target, all, options) {
83
+ if (target.legacy !== undefined) {
84
+ return [{ code: 'legacy_rule', message: 'Migrate the legacy rule to schema v2 before lifecycle changes.', ruleId: target.id }];
85
+ }
86
+ if (action === 'verify') {
87
+ if (target.status !== 'draft') {
88
+ return [{ code: 'invalid_transition', message: 'Only draft rules can be verified.', ruleId: target.id }];
89
+ }
90
+ if (options.evidence === undefined || options.evidence.trim().length === 0) {
91
+ return [{ code: 'verification_evidence_missing', message: 'Verification evidence is required.', ruleId: target.id }];
92
+ }
93
+ if (target.compatibility.scope === 'unknown') {
94
+ return [{ code: 'compatibility_unknown', message: 'Resolve compatibility before verifying the rule.', ruleId: target.id }];
95
+ }
96
+ if (target.compatibility.scope === 'constrained' &&
97
+ target.compatibility.verified_with.length === 0) {
98
+ return [{ code: 'compatibility_evidence_missing', message: 'Constrained compatibility requires verified_with evidence.', ruleId: target.id }];
99
+ }
100
+ return [];
101
+ }
102
+ if (target.status !== 'active') {
103
+ return [{ code: 'invalid_transition', message: 'Only active rules can be deprecated or superseded.', ruleId: target.id }];
104
+ }
105
+ if (action === 'deprecate') {
106
+ return [];
107
+ }
108
+ const replacement = all.find((item) => item.rule.id === options.replacement);
109
+ if (replacement === undefined) {
110
+ return [{ code: 'replacement_missing', message: `Replacement ${options.replacement ?? ''} does not exist.`, ruleId: target.id }];
111
+ }
112
+ const links = new Map(all.map((item) => [item.rule.id, item.rule.superseded_by ?? undefined]));
113
+ links.set(target.id, replacement.rule.id);
114
+ const visited = new Set();
115
+ let current = target.id;
116
+ while (current !== undefined) {
117
+ if (visited.has(current)) {
118
+ return [{ code: 'replacement_cycle', message: `Replacement graph would create a cycle at ${current}.`, ruleId: target.id }];
119
+ }
120
+ visited.add(current);
121
+ current = links.get(current);
122
+ }
123
+ if (replacement.rule.status !== 'active') {
124
+ return [{ code: 'replacement_inactive', message: 'Replacement must be active.', ruleId: replacement.rule.id }];
125
+ }
126
+ return [];
127
+ }
128
+ async function loadRuleSources(home) {
129
+ const files = await discoverRuleFiles({ rulesDir: join(home, 'rules') });
130
+ const rules = [];
131
+ const issues = [];
132
+ for (const path of files) {
133
+ const source = await readFile(path, 'utf8');
134
+ const parsed = parseRuleYaml(source, { filePath: path });
135
+ if (!parsed.success) {
136
+ issues.push({ code: 'invalid_rule_source', message: `${path}: ${parsed.error.message}` });
137
+ }
138
+ else {
139
+ rules.push({ path, source, rule: parsed.rule });
140
+ }
141
+ }
142
+ return { rules, issues };
143
+ }
144
+ function emitLifecycle(result, options) {
145
+ if (options.json === true) {
146
+ writeJson(result);
147
+ }
148
+ else {
149
+ process.stdout.write(`${result.status}\t${result.action}\t${result.ruleId}\n`);
150
+ for (const issue of result.issues) {
151
+ process.stdout.write(`issue\t${issue.code}\t${issue.message}\n`);
152
+ }
153
+ }
154
+ if (result.status !== 'updated') {
155
+ process.exitCode = 1;
156
+ }
157
+ }
158
+ //# sourceMappingURL=rule.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rule.js","sourceRoot":"","sources":["../../src/commands/rule.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,UAAU,GAEX,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,qBAAqB,GACtB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAmBxC,MAAM,UAAU,mBAAmB,CAAC,OAAgB;IAClD,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,WAAW,CAAC,6BAA6B,CAAC,CAAC;IAChF,IAAI;SACD,OAAO,CAAC,QAAQ,CAAC;SACjB,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC;SACjC,cAAc,CAAC,uBAAuB,EAAE,uBAAuB,CAAC;SAChE,MAAM,CAAC,OAAO,EAAE,sCAAsC,CAAC;SACvD,MAAM,CAAC,QAAQ,EAAE,mBAAmB,CAAC;SACrC,MAAM,CAAC,KAAK,EAAE,EAAU,EAAE,OAAyB,EAAE,EAAE;QACtD,aAAa,CAAC,MAAM,mBAAmB,CAAC,mBAAmB,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,OAAO,CAA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AAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;QAClD,CAAC;IACH,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;AAC3B,CAAC;AAED,SAAS,aAAa,CAAC,MAAuB,EAAE,OAAyB;IACvE,IAAI,OAAO,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;QAC1B,SAAS,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,MAAM,CAAC,MAAM,KAAK,MAAM,CAAC,MAAM,KAAK,MAAM,CAAC,MAAM,IAAI,CAAC,CAAC;QAC/E,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;YAClC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,OAAO,IAAI,CAAC,CAAC;QACnE,CAAC;IACH,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;QAChC,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC;AACH,CAAC"}
@@ -0,0 +1,19 @@
1
+ import type { Command } from 'commander';
2
+ import { checkRulebookIndex } from '../storage/index.js';
3
+ export type SyncIssue = {
4
+ code: string;
5
+ message: string;
6
+ path?: string;
7
+ fields?: string[];
8
+ };
9
+ export type SyncResult = {
10
+ status: 'blocked' | 'failed' | 'preview' | 'pulled' | 'pushed';
11
+ remote: string;
12
+ remoteUrl?: string;
13
+ changedFiles: string[];
14
+ issues: SyncIssue[];
15
+ index?: Awaited<ReturnType<typeof checkRulebookIndex>>;
16
+ };
17
+ export declare function registerSyncCommand(program: Command): Command;
18
+ export declare function syncPush(home: string, remote?: string, confirmed?: boolean): Promise<SyncResult>;
19
+ export declare function syncPull(home: string, remote?: string): Promise<SyncResult>;
@@ -0,0 +1,262 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { inspectRemotePrivacy, parseRuleYaml, resolveRulebookHome, runGit, scanRuleDraftForRedactions, splitGitLines, } from '../core/index.js';
4
+ import { checkRulebookIndex, rebuildRulebookIndex } from '../storage/index.js';
5
+ import { writeJson } from './output.js';
6
+ export function registerSyncCommand(program) {
7
+ const sync = program.command('sync').description('Synchronize canonical YAML with private Git');
8
+ sync
9
+ .command('pull')
10
+ .option('--remote <remote>', 'Git remote', 'origin')
11
+ .option('--json', 'Print JSON output')
12
+ .action(async (options) => emitSyncResult(await syncPull(resolveRulebookHome(), options.remote), options));
13
+ sync
14
+ .command('push')
15
+ .option('--remote <remote>', 'Git remote', 'origin')
16
+ .option('--yes', 'Push after all preflight checks pass')
17
+ .option('--json', 'Print JSON output')
18
+ .action(async (options) => emitSyncResult(await syncPush(resolveRulebookHome(), options.remote, options.yes === true), options));
19
+ return program;
20
+ }
21
+ export async function syncPush(home, remote = 'origin', confirmed = false) {
22
+ const conflicts = await conflictFiles(home);
23
+ if (conflicts.length > 0) {
24
+ return blocked(remote, await describeConflicts(home, conflicts, 'rebuild or push'));
25
+ }
26
+ const dirty = await runGit(home, ['status', '--porcelain']);
27
+ if (dirty.exitCode !== 0) {
28
+ return failed(remote, 'git_status_failed', dirty.stderr);
29
+ }
30
+ if (dirty.stdout.trim().length > 0) {
31
+ return blocked(remote, [{ code: 'worktree_dirty', message: 'Commit or discard local changes before sync push.' }]);
32
+ }
33
+ const trackedResult = await runGit(home, ['ls-files']);
34
+ if (trackedResult.exitCode !== 0) {
35
+ return failed(remote, 'git_ls_files_failed', trackedResult.stderr);
36
+ }
37
+ const tracked = splitGitLines(trackedResult.stdout);
38
+ const localArtifacts = tracked.filter(isLocalArtifact);
39
+ if (localArtifacts.length > 0) {
40
+ return blocked(remote, localArtifacts.map((path) => ({
41
+ code: 'tracked_local_artifact',
42
+ path,
43
+ message: `Remove ${path} from Git tracking; SQLite, logs, reports, temp, and lock files stay local.`,
44
+ })));
45
+ }
46
+ const nonSyncFiles = tracked.filter((path) => !isAllowedSyncPath(path));
47
+ if (nonSyncFiles.length > 0) {
48
+ return blocked(remote, nonSyncFiles.map((path) => ({
49
+ code: 'tracked_non_sync_file',
50
+ path,
51
+ message: `Remove ${path} from Git tracking; the private remote uses an explicit YAML-only allowlist.`,
52
+ })));
53
+ }
54
+ const remoteUrlResult = await runGit(home, ['remote', 'get-url', remote]);
55
+ if (remoteUrlResult.exitCode !== 0) {
56
+ return failed(remote, 'remote_missing', remoteUrlResult.stderr);
57
+ }
58
+ const remoteUrl = remoteUrlResult.stdout.trim();
59
+ const privacy = await inspectRemotePrivacy(home, remote);
60
+ if (privacy.privacy !== 'private') {
61
+ return {
62
+ status: 'blocked',
63
+ remote,
64
+ remoteUrl,
65
+ changedFiles: [],
66
+ issues: [{
67
+ code: privacy.privacy === 'public' ? 'remote_public' : 'remote_privacy_unknown',
68
+ message: privacy.privacy === 'public'
69
+ ? 'Push is disabled for public remotes.'
70
+ : privacy.evidence,
71
+ }],
72
+ };
73
+ }
74
+ const changedFiles = await filesAheadOfUpstream(home, tracked);
75
+ const boundaryIssues = changedFiles
76
+ .filter((path) => !isAllowedSyncPath(path))
77
+ .map((path) => ({ code: 'non_sync_file', path, message: 'Only canonical rules YAML and safe root config files may be synchronized.' }));
78
+ const yamlIssues = await validateChangedFiles(home, changedFiles);
79
+ const issues = [...boundaryIssues, ...yamlIssues];
80
+ if (issues.length > 0) {
81
+ return { status: 'blocked', remote, remoteUrl, changedFiles, issues };
82
+ }
83
+ if (!confirmed) {
84
+ return { status: 'preview', remote, remoteUrl, changedFiles, issues: [] };
85
+ }
86
+ const upstream = await currentUpstream(home);
87
+ const push = await runGit(home, upstream === undefined ? ['push', '--set-upstream', remote, 'HEAD'] : ['push', remote]);
88
+ if (push.exitCode !== 0) {
89
+ return { status: 'failed', remote, remoteUrl, changedFiles, issues: [{ code: 'git_push_failed', message: push.stderr.trim() }] };
90
+ }
91
+ return { status: 'pushed', remote, remoteUrl, changedFiles, issues: [] };
92
+ }
93
+ export async function syncPull(home, remote = 'origin') {
94
+ const conflicts = await conflictFiles(home);
95
+ if (conflicts.length > 0) {
96
+ return blocked(remote, await describeConflicts(home, conflicts, 'pull or rebuild'));
97
+ }
98
+ const status = await runGit(home, ['status', '--porcelain']);
99
+ if (status.exitCode !== 0) {
100
+ return failed(remote, 'git_status_failed', status.stderr);
101
+ }
102
+ if (status.stdout.trim().length > 0) {
103
+ return blocked(remote, [{ code: 'worktree_dirty', message: 'Commit or discard local changes before sync pull.' }]);
104
+ }
105
+ const pull = await runGit(home, ['pull', '--ff-only', remote]);
106
+ if (pull.exitCode !== 0) {
107
+ const afterConflicts = await conflictFiles(home);
108
+ if (afterConflicts.length > 0) {
109
+ return blocked(remote, await describeConflicts(home, afterConflicts, 'rebuild'));
110
+ }
111
+ return failed(remote, 'git_pull_failed', pull.stderr);
112
+ }
113
+ const trackedRules = await runGit(home, ['ls-files', 'rules']);
114
+ if (trackedRules.exitCode !== 0) {
115
+ return failed(remote, 'git_ls_files_failed', trackedRules.stderr);
116
+ }
117
+ const ruleFiles = splitGitLines(trackedRules.stdout);
118
+ const sourceIssues = await validateChangedFiles(home, ruleFiles);
119
+ if (sourceIssues.length > 0) {
120
+ return {
121
+ status: 'failed',
122
+ remote,
123
+ changedFiles: ruleFiles,
124
+ issues: sourceIssues,
125
+ index: await checkRulebookIndex({ home }),
126
+ };
127
+ }
128
+ let index = await checkRulebookIndex({ home });
129
+ if (index.status !== 'ok') {
130
+ await rebuildRulebookIndex({ home });
131
+ index = await checkRulebookIndex({ home });
132
+ }
133
+ return { status: 'pulled', remote, changedFiles: [], issues: [], index };
134
+ }
135
+ async function validateChangedFiles(home, files) {
136
+ const issues = [];
137
+ for (const path of files.filter((candidate) => /\.ya?ml$/i.test(candidate))) {
138
+ let source;
139
+ try {
140
+ source = await readFile(join(home, path), 'utf8');
141
+ }
142
+ catch (error) {
143
+ if (isMissingFile(error))
144
+ continue;
145
+ throw error;
146
+ }
147
+ if (!path.startsWith('rules/')) {
148
+ const scan = scanRuleDraftForRedactions({ fix: source }, { homeDir: home });
149
+ for (const warning of scan.warnings) {
150
+ issues.push({
151
+ code: warning.kind === 'secret' ? 'secret_detected' : 'redaction_required',
152
+ path,
153
+ message: `${warning.kind}: ${warning.pattern}`,
154
+ });
155
+ }
156
+ continue;
157
+ }
158
+ const parsed = parseRuleYaml(source, { filePath: path });
159
+ if (!parsed.success) {
160
+ issues.push({ code: 'invalid_rule_yaml', path, message: parsed.error.message });
161
+ continue;
162
+ }
163
+ const scan = scanRuleDraftForRedactions(parsed.rule, { homeDir: home });
164
+ for (const warning of scan.warnings) {
165
+ issues.push({
166
+ code: warning.kind === 'secret' ? 'secret_detected' : 'redaction_required',
167
+ path,
168
+ message: `${warning.field}: ${warning.pattern}`,
169
+ });
170
+ }
171
+ }
172
+ return issues;
173
+ }
174
+ function isMissingFile(error) {
175
+ return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT';
176
+ }
177
+ async function currentUpstream(home) {
178
+ const result = await runGit(home, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}']);
179
+ return result.exitCode === 0 ? result.stdout.trim() : undefined;
180
+ }
181
+ async function filesAheadOfUpstream(home, tracked) {
182
+ const upstream = await currentUpstream(home);
183
+ if (upstream === undefined) {
184
+ return tracked;
185
+ }
186
+ const result = await runGit(home, ['diff', '--name-only', `${upstream}...HEAD`]);
187
+ return result.exitCode === 0 ? splitGitLines(result.stdout) : tracked;
188
+ }
189
+ async function conflictFiles(home) {
190
+ const result = await runGit(home, ['diff', '--name-only', '--diff-filter=U']);
191
+ return result.exitCode === 0 ? splitGitLines(result.stdout) : [];
192
+ }
193
+ async function describeConflicts(home, paths, blockedAction) {
194
+ return Promise.all(paths.map(async (path) => {
195
+ let fields = [];
196
+ try {
197
+ const source = await readFile(join(home, path), 'utf8');
198
+ fields = extractConflictedYamlFields(source);
199
+ }
200
+ catch {
201
+ // The Git conflict path remains actionable even when the worktree copy cannot be read.
202
+ }
203
+ return {
204
+ code: 'git_conflict',
205
+ path,
206
+ ...(fields.length === 0 ? {} : { fields }),
207
+ message: fields.length === 0
208
+ ? `Resolve the conflicted file before ${blockedAction}.`
209
+ : `Resolve conflicted fields (${fields.join(', ')}) before ${blockedAction}.`,
210
+ };
211
+ }));
212
+ }
213
+ function extractConflictedYamlFields(source) {
214
+ const fields = new Set();
215
+ let insideConflict = false;
216
+ for (const line of source.split(/\r?\n/)) {
217
+ if (line.startsWith('<<<<<<< ')) {
218
+ insideConflict = true;
219
+ continue;
220
+ }
221
+ if (line.startsWith('>>>>>>> ')) {
222
+ insideConflict = false;
223
+ continue;
224
+ }
225
+ if (!insideConflict || line === '=======')
226
+ continue;
227
+ const match = /^\s*([A-Za-z_][A-Za-z0-9_-]*):/.exec(line);
228
+ if (match?.[1] !== undefined)
229
+ fields.add(match[1]);
230
+ }
231
+ return [...fields].sort();
232
+ }
233
+ function isAllowedSyncPath(path) {
234
+ return path === '.gitignore' || path === 'config.yaml' || path === 'config.example.yaml' || /^rules\/.+\.ya?ml$/i.test(path);
235
+ }
236
+ function isLocalArtifact(path) {
237
+ return /^(?:index|logs|reports?|migration-reports?)\//.test(path) || /(?:\.sqlite(?:-(?:wal|shm))?|\.lock|\.tmp(?:-|$))$/i.test(path);
238
+ }
239
+ function blocked(remote, issues) {
240
+ return { status: 'blocked', remote, changedFiles: [], issues };
241
+ }
242
+ function failed(remote, code, message) {
243
+ return { status: 'failed', remote, changedFiles: [], issues: [{ code, message: message.trim() }] };
244
+ }
245
+ function emitSyncResult(result, options) {
246
+ if (options.json === true) {
247
+ writeJson(result);
248
+ }
249
+ else {
250
+ process.stdout.write(`${result.status}\t${result.remote}\n`);
251
+ if (result.remoteUrl !== undefined) {
252
+ process.stdout.write(`remoteUrl\t${result.remoteUrl}\n`);
253
+ }
254
+ for (const issue of result.issues) {
255
+ process.stdout.write(`issue\t${issue.code}\t${issue.path ?? ''}\t${issue.message}\n`);
256
+ }
257
+ }
258
+ if (result.status === 'blocked' || result.status === 'failed' || result.status === 'preview') {
259
+ process.exitCode = 1;
260
+ }
261
+ }
262
+ //# sourceMappingURL=sync.js.map