shipgate-cli 0.0.0-stage → 0.2.2

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 (123) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +261 -2
  3. package/agents/context-builder.md +158 -0
  4. package/agents/debug-executor.md +234 -0
  5. package/assets/gates/classifier.js +245 -0
  6. package/assets/gates/dsh/index.js +767 -0
  7. package/assets/gates/dsh/policy.json +93 -0
  8. package/assets/gates/index.js +3 -0
  9. package/assets/gates/pi/index.js +1131 -0
  10. package/assets/gates/pi/policy.json +93 -0
  11. package/assets/gates/policy.js +4267 -0
  12. package/assets/gates/profiles/ai4s-dry-lab.json +64 -0
  13. package/assets/gates/profiles/ai4s-quant.json +36 -0
  14. package/assets/pi-extensions/auto-continue.ts +176 -0
  15. package/assets/pi-extensions/goal-mode.ts +313 -0
  16. package/bin/shipgate.mjs +9 -0
  17. package/commands/ai-spec.md +9 -0
  18. package/commands/api-first.md +33 -0
  19. package/commands/code-review.md +7 -0
  20. package/commands/codebase-context.md +19 -0
  21. package/commands/debug-ui.md +147 -0
  22. package/commands/debug.md +101 -0
  23. package/commands/dev-env-scan.md +18 -0
  24. package/commands/dev-host-init.md +28 -0
  25. package/commands/discover-skill-opportunities.md +33 -0
  26. package/commands/fork-sync.md +17 -0
  27. package/commands/gh-actions.md +26 -0
  28. package/commands/goal-driven-development.md +7 -0
  29. package/commands/intent-grill.md +7 -0
  30. package/commands/iteration-manager.md +7 -0
  31. package/commands/loop-engineer.md +21 -0
  32. package/commands/nodejs-npm-auto-release.md +12 -0
  33. package/commands/prd.md +7 -0
  34. package/commands/project-health-audit.md +7 -0
  35. package/commands/ralph-yolo.md +346 -0
  36. package/commands/ralph.md +226 -0
  37. package/commands/security-audit.md +7 -0
  38. package/commands/ux-experience-audit.md +133 -0
  39. package/docs/ARCHITECTURE.md +63 -0
  40. package/docs/GATES.md +106 -0
  41. package/docs/HARNESS.md +257 -0
  42. package/package.json +48 -4
  43. package/references/ADR-FORMAT.md +67 -0
  44. package/references/CONTEXT-FORMAT.md +62 -0
  45. package/references/mcp-config-template.json +54 -0
  46. package/scripts/fix-skill-frontmatter.mjs +66 -0
  47. package/scripts/migrate-skillpack.mjs +257 -0
  48. package/skills/ai-spec/SKILL.md +90 -0
  49. package/skills/api-first-modular/SKILL.md +411 -0
  50. package/skills/code-debugger/SKILL.md +379 -0
  51. package/skills/code-review/SKILL.md +62 -0
  52. package/skills/codebase-context/SKILL.md +139 -0
  53. package/skills/debug-ui/SKILL.md +220 -0
  54. package/skills/dev-env-scan/SKILL.md +147 -0
  55. package/skills/dev-host-init/SKILL.md +198 -0
  56. package/skills/dev-host-init/scripts/fill-placeholders.py +226 -0
  57. package/skills/dev-host-init/scripts/host-scan.ps1 +159 -0
  58. package/skills/dev-host-init/scripts/host-scan.sh +201 -0
  59. package/skills/dev-host-init/scripts/render-now.py +488 -0
  60. package/skills/dev-host-init/scripts/tools-catalog.py +229 -0
  61. package/skills/dev-host-init/templates/graph-first-gate.ts +291 -0
  62. package/skills/dev-host-init/templates/host-injection.template.md +725 -0
  63. package/skills/discover-skill-opportunities/SKILL.md +145 -0
  64. package/skills/discover-skill-opportunities/references/accounting-finance-ops.md +24 -0
  65. package/skills/discover-skill-opportunities/references/business-consulting.md +24 -0
  66. package/skills/discover-skill-opportunities/references/evidence-and-privacy.md +39 -0
  67. package/skills/discover-skill-opportunities/references/finance-investment.md +24 -0
  68. package/skills/discover-skill-opportunities/references/legal-and-compliance.md +24 -0
  69. package/skills/discover-skill-opportunities/references/output-contract.md +75 -0
  70. package/skills/discover-skill-opportunities/references/product-and-operations.md +24 -0
  71. package/skills/discover-skill-opportunities/references/quant-trading.md +24 -0
  72. package/skills/discover-skill-opportunities/references/scientific-research.md +24 -0
  73. package/skills/discover-skill-opportunities/references/scoring-rubric.md +45 -0
  74. package/skills/discover-skill-opportunities/references/session-skill-review.md +78 -0
  75. package/skills/discover-skill-opportunities/references/software-development.md +24 -0
  76. package/skills/fork-sync/SKILL.md +86 -0
  77. package/skills/gh-actions-architect/SKILL.md +395 -0
  78. package/skills/goal-driven-development/SKILL.md +132 -0
  79. package/skills/intent-grill/SKILL.md +46 -0
  80. package/skills/iteration-manager/SKILL.md +53 -0
  81. package/skills/loop-engineer/SKILL.md +108 -0
  82. package/skills/nodejs-npm-auto-release/SKILL.md +141 -0
  83. package/skills/prd/SKILL.md +63 -0
  84. package/skills/project-health-audit/SKILL.md +64 -0
  85. package/skills/ralph/SKILL.md +329 -0
  86. package/skills/ralph-yolo/SKILL.md +623 -0
  87. package/skills/security-audit/SKILL.md +114 -0
  88. package/skills/security-audit/references/audit-checklist.md +135 -0
  89. package/skills/security-audit/references/evidence-conventions.md +54 -0
  90. package/skills/security-audit/references/findings-schema.md +37 -0
  91. package/skills/security-audit/references/stack-signatures.md +66 -0
  92. package/skills/shipgate/SKILL.md +40 -0
  93. package/skills/shipgate-install/SKILL.md +87 -0
  94. package/skills/shipgate-quality/SKILL.md +80 -0
  95. package/skills/shipgate-security/SKILL.md +97 -0
  96. package/skills/shipgate-spec/SKILL.md +67 -0
  97. package/skills/ux-experience-audit/SKILL.md +202 -0
  98. package/src/cli.mjs +118 -0
  99. package/src/commands/ask.mjs +82 -0
  100. package/src/commands/deploy.mjs +587 -0
  101. package/src/commands/gates.mjs +83 -0
  102. package/src/commands/policy.mjs +116 -0
  103. package/src/gates/quality.mjs +123 -0
  104. package/src/gates/security.mjs +92 -0
  105. package/src/gates/ship.mjs +74 -0
  106. package/src/gates/spec.mjs +88 -0
  107. package/src/harness/index.mjs +203 -0
  108. package/src/inject/render.mjs +75 -0
  109. package/src/lib/cfg.mjs +66 -0
  110. package/src/lib/duration.mjs +41 -0
  111. package/src/lib/engines.mjs +182 -0
  112. package/src/lib/exec.mjs +80 -0
  113. package/src/lib/fsx.mjs +119 -0
  114. package/src/lib/gate.mjs +329 -0
  115. package/src/lib/log.mjs +31 -0
  116. package/src/lib/skills.mjs +347 -0
  117. package/src/lib/state.mjs +50 -0
  118. package/src/lib/update.mjs +67 -0
  119. package/src/version.mjs +14 -0
  120. package/templates/agents-snippet.md +82 -0
  121. package/templates/dev-profile.schema.json +119 -0
  122. package/templates/prd.json.example +64 -0
  123. package/templates/rule.json.example +28 -0
@@ -0,0 +1,119 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+
5
+ export function exists(p) {
6
+ return fs.existsSync(p);
7
+ }
8
+
9
+ export function readText(p) {
10
+ return fs.readFileSync(p, 'utf8');
11
+ }
12
+
13
+ export function readIfExists(p) {
14
+ return exists(p) ? readText(p) : null;
15
+ }
16
+
17
+ export function ensureDir(p) {
18
+ fs.mkdirSync(p, { recursive: true });
19
+ return p;
20
+ }
21
+
22
+ export function writeText(p, text) {
23
+ ensureDir(path.dirname(p));
24
+ fs.writeFileSync(p, text);
25
+ }
26
+
27
+ /**
28
+ * Symlink and junction detection. On Windows a directory junction reports
29
+ * isSymbolicLink() === true, which is what we want: `~/.agents/skills` is a
30
+ * link either way and writing through it must be recognised, not treated as a
31
+ * plain directory.
32
+ */
33
+ export function isSymlink(p) {
34
+ try {
35
+ return fs.lstatSync(p).isSymbolicLink();
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+
41
+ export function realpathOrNull(p) {
42
+ try {
43
+ return fs.realpathSync(p);
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ export function listDir(p) {
50
+ if (!exists(p)) return [];
51
+ return fs.readdirSync(p, { withFileTypes: true });
52
+ }
53
+
54
+ export function hashText(text) {
55
+ return crypto.createHash('sha256').update(text).digest('hex').slice(0, 16);
56
+ }
57
+
58
+ export function hashFile(p) {
59
+ return hashText(fs.readFileSync(p));
60
+ }
61
+
62
+ export function copyTree(src, dest, { skip = [] } = {}) {
63
+ const written = [];
64
+ ensureDir(dest);
65
+ for (const entry of listDir(src)) {
66
+ if (skip.includes(entry.name)) continue;
67
+ const from = path.join(src, entry.name);
68
+ const to = path.join(dest, entry.name);
69
+ if (entry.isDirectory()) {
70
+ written.push(...copyTree(from, to, { skip }));
71
+ } else if (entry.isFile()) {
72
+ fs.copyFileSync(from, to);
73
+ written.push(to);
74
+ }
75
+ }
76
+ return written;
77
+ }
78
+
79
+ export function removeDir(p) {
80
+ fs.rmSync(p, { recursive: true, force: true });
81
+ }
82
+
83
+ export function today() {
84
+ return new Date().toISOString().slice(0, 10);
85
+ }
86
+
87
+ /**
88
+ * One backup per file per day. Backups of user-authored entry docs are the only
89
+ * safety net for inject/revoke, so the name is deterministic: <file>.shipgate-bak.<YYYYMMDD>
90
+ */
91
+ export function backupOnce(file) {
92
+ if (!exists(file)) return null;
93
+ const target = `${file}.shipgate-bak.${today()}`;
94
+ if (exists(target)) return target;
95
+ fs.copyFileSync(file, target);
96
+ return target;
97
+ }
98
+
99
+ export function backupList(file) {
100
+ const dir = path.dirname(file);
101
+ const base = path.basename(file) + '.shipgate-bak.';
102
+ return listDir(dir)
103
+ .filter((e) => e.isFile() && e.name.startsWith(base))
104
+ .map((e) => path.join(dir, e.name))
105
+ .sort();
106
+ }
107
+
108
+ export function latestBackup(file) {
109
+ return backupList(file).at(-1) ?? null;
110
+ }
111
+
112
+ /**
113
+ * The oldest backup is the only one taken before ShipGate ever wrote to the
114
+ * file. `revoke` must use it: restoring the latest would put back an older
115
+ * injected block instead of the user's original document.
116
+ */
117
+ export function earliestBackup(file) {
118
+ return backupList(file)[0] ?? null;
119
+ }
@@ -0,0 +1,329 @@
1
+ import path from 'node:path';
2
+ import { HOME } from './cfg.mjs';
3
+ import { stateDir } from './state.mjs';
4
+ import { packageRoot } from '../version.mjs';
5
+ import { backupOnce, copyTree, exists, listDir, readIfExists, writeText } from './fsx.mjs';
6
+
7
+ const DEFAULT_POLICY = {
8
+ config: {
9
+ destructive_mode: 'enforce',
10
+ destructive_mode_until: 0,
11
+ protected_worktrees: [],
12
+ },
13
+ };
14
+
15
+ export function globalPolicyPath() {
16
+ return path.join(stateDir(), 'gate-policy.json');
17
+ }
18
+
19
+ export function gatesSource() {
20
+ return path.join(packageRoot(), 'assets', 'gates');
21
+ }
22
+
23
+ /**
24
+ * Single source of truth for gate policy. Harness policy.json files are
25
+ * projections of this file, so `policy --sync` can always rebuild them.
26
+ */
27
+ export function loadPolicy(dir = stateDir()) {
28
+ const text = readIfExists(path.join(dir, 'gate-policy.json'));
29
+ if (text === null) return structuredClone(DEFAULT_POLICY);
30
+ try {
31
+ const parsed = JSON.parse(text);
32
+ return { ...structuredClone(DEFAULT_POLICY), ...parsed, config: { ...DEFAULT_POLICY.config, ...(parsed.config ?? {}) } };
33
+ } catch (error) {
34
+ throw new Error(`gate-policy.json 损坏,请检查 ${path.join(dir, 'gate-policy.json')}:${error.message}`);
35
+ }
36
+ }
37
+
38
+ export function savePolicy(policy, dir = stateDir()) {
39
+ writeText(path.join(dir, 'gate-policy.json'), JSON.stringify(policy, null, 2) + '\n');
40
+ return policy;
41
+ }
42
+
43
+ function normalizeDir(dir) {
44
+ return path.resolve(dir.startsWith('~') ? path.join(HOME, dir.slice(1)) : dir);
45
+ }
46
+
47
+ export function addProtected(dir) {
48
+ const policy = loadPolicy();
49
+ const target = normalizeDir(dir);
50
+ const list = policy.config.protected_worktrees ?? [];
51
+ if (!list.includes(target)) list.push(target);
52
+ policy.config.protected_worktrees = list;
53
+ return savePolicy(policy);
54
+ }
55
+
56
+ export function removeProtected(dir) {
57
+ const policy = loadPolicy();
58
+ const target = normalizeDir(dir);
59
+ policy.config.protected_worktrees = (policy.config.protected_worktrees ?? []).filter((p) => p !== target);
60
+ return savePolicy(policy);
61
+ }
62
+
63
+ /**
64
+ * Write the one truth the gate actually reads.
65
+ *
66
+ * `durationMs` is what makes a bypass bounded. `enforce` never keeps an expiry:
67
+ * nothing reads `until` on an enforce record today, but a stale deadline would
68
+ * silently shorten the next bypass the user asks for.
69
+ */
70
+ export function setMode(mode, { durationMs = 0, now = Date.now(), dir = stateDir() } = {}) {
71
+ if (!['enforce', 'bypass'].includes(mode)) {
72
+ throw new Error(`destructive_mode 只能是 enforce 或 bypass,收到:${mode}`);
73
+ }
74
+ if (mode === 'enforce' && durationMs > 0) {
75
+ throw new Error('enforce 不接受时长:带时长的是有界 bypass,enforce 只会立刻生效。');
76
+ }
77
+ const policy = loadPolicy(dir);
78
+ policy.config.destructive_mode = mode;
79
+ policy.config.destructive_mode_until = mode === 'bypass' && durationMs > 0 ? now + durationMs : 0;
80
+ return savePolicy(policy, dir);
81
+ }
82
+
83
+ /**
84
+ * What the stored policy actually means right now.
85
+ *
86
+ * The engine already reads an expired `until` as enforce (its `effectiveDestructiveMode`).
87
+ * The CLI used to print the raw file instead, so a bypass that had already
88
+ * expired still showed as BYPASS - the same "the surface disagrees with the
89
+ * runtime" failure this whole change exists to remove.
90
+ */
91
+ export function policyModeView(policy, now = Date.now()) {
92
+ const stored = policy?.config?.destructive_mode === 'bypass' ? 'bypass' : 'enforce';
93
+ const until = Number(policy?.config?.destructive_mode_until ?? 0) || 0;
94
+ const expired = stored === 'bypass' && until > 0 && now >= until;
95
+ return {
96
+ stored,
97
+ mode: expired ? 'enforce' : stored,
98
+ until,
99
+ remainingMs: stored === 'bypass' && until > 0 ? Math.max(0, until - now) : null,
100
+ expired,
101
+ };
102
+ }
103
+
104
+ /**
105
+ * Merge rule: the base document supplies the rules (checks / reminder /
106
+ * description / version), `config` is layered as base defaults ← harness-local
107
+ * ← global truth, and protected worktrees are unioned so a harness never
108
+ * silently loses a protection the operator just added.
109
+ *
110
+ * The global policy deliberately contributes **only** `config`: it used to be
111
+ * spread whole, which let one harness's stale copy become the next harness's
112
+ * shipped rules.
113
+ */
114
+ export function mergePolicy(globalPolicy, base, harnessConfig = {}) {
115
+ const document = base && typeof base === 'object' ? base : {};
116
+ const baseConfig = document.config && typeof document.config === 'object' ? document.config : {};
117
+ const localConfig = harnessConfig && typeof harnessConfig === 'object' ? harnessConfig : {};
118
+ const union = [
119
+ ...new Set([
120
+ ...(globalPolicy.config.protected_worktrees ?? []),
121
+ ...(localConfig.protected_worktrees ?? []),
122
+ ...(baseConfig.protected_worktrees ?? []),
123
+ ]),
124
+ ];
125
+ return {
126
+ ...document,
127
+ config: { ...baseConfig, ...localConfig, ...globalPolicy.config, protected_worktrees: union },
128
+ };
129
+ }
130
+
131
+ function readJson(file) {
132
+ const text = readIfExists(file);
133
+ if (text === null) return null;
134
+ try {
135
+ return JSON.parse(text);
136
+ } catch {
137
+ // A malformed harness policy is not silently discarded: we keep the raw
138
+ // file under a backup name and let the caller re-seed from global policy.
139
+ return { __malformed: true };
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Sync projection: the global policy is authoritative, so protected worktrees
145
+ * are replaced rather than unioned. Unioning here would make --rm-protected
146
+ * impossible to apply (the removed entry keeps coming back from the harness
147
+ * copy). Union happens exactly once, at install time, and is then promoted
148
+ * back to the global file.
149
+ */
150
+ export function projectPolicy(globalPolicy, existing) {
151
+ const base = existing && typeof existing === 'object' ? existing : {};
152
+ const existingConfig = base.config && typeof base.config === 'object' ? base.config : {};
153
+ return {
154
+ ...base,
155
+ config: {
156
+ ...existingConfig,
157
+ ...globalPolicy.config,
158
+ protected_worktrees: [...(globalPolicy.config.protected_worktrees ?? [])],
159
+ },
160
+ };
161
+ }
162
+
163
+ /**
164
+ * Entry point each harness loads. The vendored `assets/gates/index.js` is the pi
165
+ * entry; copying it verbatim hands dsh a pi plugin, so the matching entry is
166
+ * written at install time.
167
+ */
168
+ const GATE_ENTRY = {
169
+ pi: "// pi loads a directory's index.js as the extension entry.\nexport { default } from './pi/index.js';\n",
170
+ dsh: "// dsh mounts a module specifier; index.js stays a valid entry too.\nexport { apply, inject } from './dsh/index.js';\n",
171
+ };
172
+
173
+ /** The shipped policy document for one harness kind (pi v6 / dsh v7), or null. */
174
+ export function shippedPolicy(kind) {
175
+ const parsed = readJson(path.join(gatesSource(), kind, 'policy.json'));
176
+ return parsed && !parsed.__malformed ? parsed : null;
177
+ }
178
+
179
+ export function installGateBundle(harness, { dryRun = false } = {}) {
180
+ if (!harness.gateDest) return { action: 'none' };
181
+ const source = gatesSource();
182
+ if (!exists(source)) return { action: 'missing-source', source };
183
+
184
+ const kind = harness.gate?.kind ?? 'pi';
185
+ const target = path.join(harness.gateDest, 'policy.json');
186
+ const existing = readJson(target);
187
+ const globalPolicy = loadPolicy();
188
+
189
+ // The document must come from the shipped per-kind file. Promoting whatever
190
+ // the harness already had is exactly how a stale v5 copy overwrote the v6/v7
191
+ // rules on the next install.
192
+ const shipped = shippedPolicy(kind);
193
+ const current = existing && !existing.__malformed ? existing : null;
194
+ const base = shipped ?? current ?? globalPolicy;
195
+ const localConfig = current?.config ?? {};
196
+ const merged = mergePolicy(globalPolicy, base, localConfig);
197
+
198
+ if (!dryRun) {
199
+ copyTree(source, harness.gateDest, { skip: ['policy.json'] });
200
+ if (exists(target)) backupOnce(target);
201
+ writeText(target, JSON.stringify(merged, null, 2) + '\n');
202
+ writeText(path.join(harness.gateDest, 'index.js'), GATE_ENTRY[kind] ?? GATE_ENTRY.pi);
203
+ if (kind === 'dsh') {
204
+ // dsh loads the bundle as ESM. Without this, Node resolves `.js` as
205
+ // CommonJS and the plugin dies on `export` before any rule can run.
206
+ writeText(path.join(harness.gateDest, 'package.json'), JSON.stringify({ type: 'module' }, null, 2) + '\n');
207
+ }
208
+ // The truth source keeps CONFIG only: promoting the document is what made
209
+ // one harness's copy become the other harness's rules.
210
+ savePolicy({ config: merged.config });
211
+ }
212
+
213
+ return { action: dryRun ? 'would-install' : 'installed', kind, target, version: merged.version ?? null };
214
+ }
215
+
216
+ export function syncPolicyToHarnesses(harnesses, { dryRun = false } = {}) {
217
+ const globalPolicy = loadPolicy();
218
+ const touched = [];
219
+
220
+ for (const harness of harnesses) {
221
+ if (!harness.gateDest) continue;
222
+ const target = path.join(harness.gateDest, 'policy.json');
223
+ if (!exists(harness.gateDest)) continue;
224
+ const existing = readJson(target);
225
+ // A harness whose policy file went missing is re-seeded from its own
226
+ // shipped document, not from whichever document happens to be in truth.
227
+ const base = existing && !existing.__malformed ? existing : shippedPolicy(harness.gate?.kind ?? 'pi');
228
+ const merged = projectPolicy(globalPolicy, base);
229
+ if (!dryRun) {
230
+ if (exists(target)) backupOnce(target);
231
+ writeText(target, JSON.stringify(merged, null, 2) + '\n');
232
+ }
233
+ touched.push({ harness: harness.id, target, mode: merged.config.destructive_mode, protected: merged.config.protected_worktrees.length });
234
+ }
235
+ return touched;
236
+ }
237
+
238
+ export function gateStatus(harness) {
239
+ if (!harness.gateDest) return { installed: false, reason: 'harness 无 gate 配置' };
240
+ if (!exists(harness.gateDest)) return { installed: false, reason: '目录不存在' };
241
+ const policy = readJson(path.join(harness.gateDest, 'policy.json'));
242
+ const view = policyModeView(policy ?? {});
243
+ return {
244
+ installed: exists(path.join(harness.gateDest, 'policy.js')) && exists(path.join(harness.gateDest, 'classifier.js')),
245
+ dir: harness.gateDest,
246
+ // The effective mode, not the raw field: an expired bypass is enforce.
247
+ mode: view.mode,
248
+ storedMode: view.stored,
249
+ modeUntil: view.until,
250
+ protected: policy?.config?.protected_worktrees?.length ?? 0,
251
+ };
252
+ }
253
+
254
+ /**
255
+ * Scan dsh Cordis patch files for the gate row actually composed into the
256
+ * runtime. dsh does not auto-load an extensions directory: whatever the patch
257
+ * points at is what runs, so "installed" alone does not mean "in effect".
258
+ */
259
+ function scanDshMounts(profilesDir) {
260
+ const mounted = [];
261
+ for (const entry of listDir(profilesDir)) {
262
+ if (!entry.isDirectory()) continue;
263
+ const patch = path.join(profilesDir, entry.name, 'cordis.patch.yml');
264
+ const text = readIfExists(patch);
265
+ if (!text) continue;
266
+ for (const line of text.split(/\r?\n/)) {
267
+ if (!/^\s*name\s*:/.test(line)) continue;
268
+ if (/enforce-rules/.test(line)) mounted.push('enforce-rules');
269
+ else if (/agent-config-gates/.test(line)) mounted.push('agent-config-gates');
270
+ else if (/coding-gateways/.test(line)) mounted.push('coding-gateways');
271
+ }
272
+ }
273
+ return [...new Set(mounted)];
274
+ }
275
+
276
+ /**
277
+ * A directory only counts as a gate if it carries the engine. Without this
278
+ * check, any unrelated extension (e.g. a provider gateway that happens to live
279
+ * in the same folder) is mistaken for a second gate — and the operator is told
280
+ * to move an extension whose removal would break their model access.
281
+ */
282
+ function isGateBundle(dir) {
283
+ return exists(path.join(dir, 'policy.js')) || exists(path.join(dir, 'classifier.js'));
284
+ }
285
+
286
+ function otherGateBundles(extensionsDir, ownName) {
287
+ return listDir(extensionsDir)
288
+ .filter((entry) => entry.isDirectory() && entry.name !== ownName)
289
+ .map((entry) => path.join(extensionsDir, entry.name))
290
+ .filter(isGateBundle);
291
+ }
292
+
293
+ /**
294
+ * Detect gate artefacts from agent-config-bridge that would run alongside
295
+ * ShipGate's own bundle. This is a report-only probe: deleting another
296
+ * project's files is never automatic. The caller prints the findings and hands
297
+ * over an explicit command.
298
+ */
299
+ export function detectLegacyGates({ home = HOME } = {}) {
300
+ const piExtDir = path.join(home, '.pi', 'agent', 'extensions');
301
+ const shipGatePi = path.join(piExtDir, 'enforce-rules');
302
+ // bridge's pi gate used install_as "enforce-rules" — the SAME directory
303
+ // ShipGate uses. A second pi gate therefore only exists if some OTHER folder
304
+ // holds a real gate bundle; a plain provider extension must not match.
305
+ const rivalGates = exists(shipGatePi) ? otherGateBundles(piExtDir, 'enforce-rules') : [];
306
+ const dshGate = path.join(home, '.dsh', 'plugins', 'agent-config-gates');
307
+ // The old bridge override. Since CHG-20261128-machine-override-single-source
308
+ // the live gate reads `~/.config/shipgate/machine-override.json` and drops any
309
+ // `destructive_mode` it finds in an override file, so this one is clutter
310
+ // (mode included) rather than a second source of truth.
311
+ const legacyOverride = path.join(home, '.config', 'agent-config-bridge', 'gate-policy.json');
312
+
313
+ const legacyOverrideMode = (() => {
314
+ const parsed = readJson(legacyOverride);
315
+ return parsed && !parsed.__malformed ? (parsed.config?.destructive_mode ?? 'unknown') : 'unknown';
316
+ })();
317
+
318
+ return {
319
+ bridgePiGate: rivalGates[0] ?? null,
320
+ rivalGates,
321
+ shipGatePi: exists(shipGatePi) ? shipGatePi : null,
322
+ bridgeDshGate: exists(dshGate) && isGateBundle(dshGate) ? dshGate : null,
323
+ bridgePolicy: exists(legacyOverride) ? legacyOverride : null,
324
+ legacyOverride: exists(legacyOverride) ? legacyOverride : null,
325
+ bridgePolicyMode: legacyOverrideMode,
326
+ legacyOverrideMode,
327
+ dshMounted: scanDshMounts(path.join(home, '.dsh', 'profiles')),
328
+ };
329
+ }
@@ -0,0 +1,31 @@
1
+ const colorEnabled = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
2
+
3
+ const paint = (code, text) => (colorEnabled ? `\u001b[${code}m${text}\u001b[0m` : String(text));
4
+
5
+ export const c = {
6
+ bold: (s) => paint('1', s),
7
+ dim: (s) => paint('2', s),
8
+ green: (s) => paint('32', s),
9
+ yellow: (s) => paint('33', s),
10
+ red: (s) => paint('31', s),
11
+ cyan: (s) => paint('36', s),
12
+ };
13
+
14
+ export const log = {
15
+ plain: (...args) => console.log(...args),
16
+ info: (msg) => console.log(msg),
17
+ ok: (msg) => console.log(`${c.green('✔')} ${msg}`),
18
+ warn: (msg) => console.log(`${c.yellow('▲')} ${msg}`),
19
+ err: (msg) => console.error(`${c.red('✖')} ${msg}`),
20
+ step: (msg) => console.log(`${c.cyan('▸')} ${msg}`),
21
+ title: (msg) => console.log(`\n${c.bold(msg)}`),
22
+ };
23
+
24
+ export function table(rows, headers) {
25
+ if (rows.length === 0) return '';
26
+ const all = [headers, ...rows];
27
+ const widths = headers.map((_, i) => Math.max(...all.map((r) => String(r[i] ?? '').length)));
28
+ return all
29
+ .map((row) => row.map((cell, i) => String(cell ?? '').padEnd(widths[i])).join(' ').trimEnd())
30
+ .join('\n');
31
+ }