shipgate-cli 0.2.1 → 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.
package/README.md CHANGED
@@ -22,7 +22,7 @@
22
22
  ```bash
23
23
  # 1) 交互式(推荐):列出探测到的 agent,逐个确认
24
24
  npx shipgate-cli install --ask
25
- # ↑ 包未发布到 npm 时改用仓库本地(效果完全一致):
25
+ # ↑ 也可以从源码直接装(效果完全一致,适合改代码时):
26
26
  # git clone https://github.com/hhx465453939/ShipGate.git && cd ShipGate
27
27
  # node bin/shipgate.mjs install --ask
28
28
 
@@ -36,8 +36,7 @@ shipgate install --harness claude,pi,codex
36
36
  shipgate install --dry-run # 只看计划,不写盘
37
37
  ```
38
38
 
39
- > 维护者发布:`npm login` 后 `cd ShipGate && npm publish`(包名 `shipgate-cli`,安装后的命令仍是 `shipgate`)。
40
- > `npm publish --dry-run` 已验证通过:299 kB / 119 files。
39
+ > 包名 `shipgate-cli`,安装后的命令仍是 `shipgate`。发版走 CI(推 `v*` tag 或手动 dispatch),流程与 `NPM_TOKEN` 配置见下文「发版与 CI/CD」。当前发布物:332 kB / 122 files(含 27 个 skill,`bin/shipgate.mjs` 权限 0755)。
41
40
 
42
41
  引擎(ShipGate 只检查,不替你装):
43
42
 
@@ -186,38 +185,41 @@ node scripts/migrate-skillpack.mjs --check # 技能包 frontmatter 体检
186
185
 
187
186
  push main **不会**发版:发布开关只有「打 tag」和「手动 dispatch」两个,发布权留在人手上。
188
187
 
189
- ### 一次性配置:NPM_TOKEN
188
+ ### 一次性配置:Trusted Publisher(OIDC,推荐)
190
189
 
191
- `release` 的发布步骤读仓库 secret `NPM_TOKEN`。配一次即可,之后所有发版都走它。
190
+ `release` 默认用 **OIDC(npm Trusted Publishing)** 发布:GitHub 每次发布签一张短时凭据,仓库里不再需要长期 token,也不受 2FA 影响。
192
191
 
193
- **第 1 步:在 npm 建 token**
192
+ **在 npm 包设置里绑定一次**
194
193
 
195
- 1. 登录 <https://www.npmjs.com/> → 右上头像 → **Access Tokens** → **Generate New Token**。
196
- 2. 选 **Granular Access Token**(推荐):
197
- - **Token name**:随便写,例如 `shipgate-github-actions`;
198
- - **Expiration**:按需(例如 90 天,到期需换新);
199
- - **Packages and scopes** → 选 **Read and write**;
200
- - **Packages** 选 **All packages**(首次发布时包还不存在,无法预先勾选单包;发布后可以收紧成只勾 `shipgate-cli`);
201
- - **Organizations** 不用动;
202
- - 建完立刻复制那条 `npm_...` 开头的 token(**只显示一次**)。
203
- - 旧式 **Classic → Automation** token 也能用,权限更粗但配起来最快。
204
- 3. 开了账号 2FA 的话,选 Automation/Granular 才不会被要求交互式 OTP。
205
-
206
- **第 2 步:把 token 存成 GitHub secret**
207
-
208
- 仓库 → **Settings** → **Secrets and variables** → **Actions** → **New repository secret**:
194
+ 打开 <https://www.npmjs.com/package/shipgate-cli> → **Settings** → 找到 **Trusted Publisher** → 选 **GitHub Actions**:
209
195
 
210
196
  | 字段 | 值 |
211
197
  |---|---|
212
- | Name | `NPM_TOKEN`(必须一字不差) |
213
- | Secret | 上一步复制的 `npm_...` |
198
+ | Organization or user | `hhx465453939` |
199
+ | Repository | `ShipGate` |
200
+ | Workflow filename | `release.yml`(只写文件名,含扩展名) |
201
+ | Environment name | 留空 |
202
+ | Allowed actions | **必须勾上 `npm publish`**(默认只给 `npm stage publish`,不勾会被拒) |
203
+
204
+ CLI 等价写法(本机先 `npm login`,账号已开 2FA):
205
+
206
+ ```bash
207
+ npm trust github shipgate-cli \
208
+ --repo hhx465453939/ShipGate \
209
+ --file release.yml \
210
+ --allow-publish
211
+ ```
214
212
 
215
- 命令行等价写法(会提示粘贴,不回显):
213
+ **备选:长期 token(OIDC 不可用时)**
214
+
215
+ 暂时不想绑 OIDC 也能发:npm → Access Tokens → Granular(**Read and write** + **All packages**,并取消勾选 `Require two-factor authentication for write actions`),或 Classic **Automation**。然后:
216
216
 
217
217
  ```bash
218
218
  gh secret set NPM_TOKEN --repo hhx465453939/ShipGate
219
219
  ```
220
220
 
221
+ token 只是兜底:npm 优先用 OIDC,OIDC 失败才回退 token。绑定验证通过后可以删掉这个 secret。
222
+
221
223
  ### 发版三步
222
224
 
223
225
  ```bash
@@ -238,7 +240,8 @@ gh run watch
238
240
  发版后的排错口径:
239
241
 
240
242
  - **JOB 绿但没发出去** → 看 `版本是否已发布(幂等)` 步骤,`::notice::` 说明该版本已在 npm,属预期跳过。
241
- - **`ENEEDAUTH` / `need auth`** → 仓库里没有名为 `NPM_TOKEN` 的 secret(名字写错也算没有)。GitHub 不支持给 secret 改名:新建一个 `NPM_TOKEN` 粘贴同一个 token 值,再删旧名。
243
+ - **绑了 OIDC 仍被拒** → 检查 `Allowed actions` 是否勾了 `npm publish`(默认只给 `npm stage publish`);再核对仓库名、workflow 文件名(只写 `release.yml`),以及 runner 必须是 GitHub-hosted(npm 不支持自建 runner 的 OIDC)。
244
+ - **`ENEEDAUTH` / `need auth`** → 既没有 OIDC 绑定,也没有可用的 `NPM_TOKEN`。先确认 npm 包绑了 Trusted Publisher;若走 token 路线,确认 secret 名一字不差是 `NPM_TOKEN`(GitHub 不支持改名,需新建后删旧名)。
242
245
  - **`EOTP`(要一次性密码)** → token 本身有效,但没有「免 2FA 写操作」属性。账号开了 2FA 时这样就必须重走 token,二选一:
243
246
  - **Classic** 类型选 **Automation**(天然免 OTP,最省事);
244
247
  - **Granular** 类型在创建页**取消勾选** `Require two-factor authentication for write actions`。
@@ -13,6 +13,7 @@
13
13
  * snapshots them and `revoke` removes them again.
14
14
  */
15
15
 
16
+ import { spawnSync } from 'node:child_process';
16
17
  import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
17
18
  import { dirname, join } from 'node:path';
18
19
  import { fileURLToPath } from 'node:url';
@@ -269,7 +270,27 @@ export default function enforceRules(pi, options = {}) {
269
270
  * `bridge apply` - and it keeps the installed `policy.json` and the live
270
271
  * override from ever disagreeing about a tier.
271
272
  */
272
- const policy = applyMachineOverride(loadedPolicy);
273
+ let policy = applyMachineOverride(loadedPolicy);
274
+
275
+ /**
276
+ * Re-read the policy this adapter booted from.
277
+ *
278
+ * `/gate mode` writes ShipGate's truth source, and the CLI projects the new
279
+ * mode into this harness's `policy.json`. Without a reload the running session
280
+ * keeps its boot snapshot: the switch would report success while the gate still
281
+ * applied the old mode until pi restarts - the exact "wrote it, nobody read it"
282
+ * failure this command used to have.
283
+ *
284
+ * `options.policy` means the caller injected a document; it owns reloading.
285
+ */
286
+ const reloadPolicy = () => {
287
+ if (options.policy || !resolved) return null;
288
+ const fresh = loadPolicy(resolved);
289
+ if (!fresh.ok) return `重读 ${resolved} 失败:${fresh.error}`;
290
+ policy = applyMachineOverride(fresh.policy);
291
+ resetMtimeCache();
292
+ return null;
293
+ };
273
294
 
274
295
  const state = newSessionState();
275
296
  /** Set once per session so the same advisory is not repeated. */
@@ -798,41 +819,6 @@ export default function enforceRules(pi, options = {}) {
798
819
  const category = tokens[1] ?? null;
799
820
  const categories = Object.keys(DESTRUCTIVE_CATEGORIES);
800
821
 
801
- /**
802
- * The machine-local override, read once per command.
803
- *
804
- * Factored out because BOTH the grant path and the mode path write this
805
- * file; two hand-rolled parsers is how one of them ends up silently
806
- * dropping the other's keys.
807
- */
808
- const readGateDoc = () => {
809
- const file = machineGateConfigPath();
810
- if (!file) {
811
- return { error: '无法定位机器本地配置目录(HOME / USERPROFILE 均未设置)。' };
812
- }
813
- let doc = {};
814
- if (existsSync(file)) {
815
- try {
816
- doc = JSON.parse(readFileSync(file, 'utf8')) ?? {};
817
- } catch (err) {
818
- return { error: `${file} 不是合法 JSON,先修好它:${err.message}` };
819
- }
820
- }
821
- if (!doc || typeof doc !== 'object' || Array.isArray(doc)) doc = {};
822
- if (!doc.config || typeof doc.config !== 'object' || Array.isArray(doc.config)) doc.config = {};
823
- return { file, doc };
824
- };
825
-
826
- const writeGateDoc = (file, doc) => {
827
- try {
828
- mkdirSync(dirname(file), { recursive: true });
829
- writeFileSync(file, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
830
- return null;
831
- } catch (err) {
832
- return `写入 ${file} 失败:${err.message}`;
833
- }
834
- };
835
-
836
822
  /** Everything the mode banner and the picker need, in one read. */
837
823
  const modeState = () => {
838
824
  const merged = applyMachineOverride(policy);
@@ -882,6 +868,9 @@ export default function enforceRules(pi, options = {}) {
882
868
  ' /gate mode enforce 全局 enforce',
883
869
  ' /gate mode bypass session 仅本会话 bypass(不写盘,重开会话失效)',
884
870
  ' /gate mode enforce session 仅本会话 enforce(覆盖全局)',
871
+ '',
872
+ ' 持久切换写 ShipGate 真源 ~/.config/shipgate/gate-policy.json(经 shipgate policy --mode),',
873
+ ' 并由它同步到本机所有 harness;machine-override.json 只存授权档位与受保护目录。',
885
874
  ].join('\n');
886
875
 
887
876
  const report = () => {
@@ -938,6 +927,7 @@ export default function enforceRules(pi, options = {}) {
938
927
  let action = '';
939
928
  let sessionScope = false;
940
929
  let durationMs = null;
930
+ let durationToken = null;
941
931
 
942
932
  for (const word of modeTokens) {
943
933
  const lower = word.toLowerCase();
@@ -958,6 +948,7 @@ export default function enforceRules(pi, options = {}) {
958
948
  return;
959
949
  }
960
950
  durationMs = parsed;
951
+ durationToken = word;
961
952
  }
962
953
  // `/gate mode 8h` is an unambiguous request for a bounded bypass.
963
954
  if (!action && durationMs !== null) action = 'bypass';
@@ -1005,32 +996,51 @@ export default function enforceRules(pi, options = {}) {
1005
996
  return;
1006
997
  }
1007
998
 
1008
- const read = readGateDoc();
1009
- if (read.error) {
1010
- notify(read.error, 'error');
1011
- return;
1012
- }
1013
- read.doc.config.destructive_mode = action;
1014
- read.doc.config.destructive_mode_until =
1015
- action === 'bypass' && durationMs ? Date.now() + durationMs : 0;
1016
- const failure = writeGateDoc(read.file, read.doc);
1017
- if (failure) {
1018
- notify(failure, 'error');
999
+ // The truth source is written by ShipGate, never by this adapter: one
1000
+ // writer means the file the gate reads and the mode the user sees are
1001
+ // the same fact. `--until` is the CLI's grammar, so the token is passed
1002
+ // through verbatim - `parseGateDurationMs` above already rejected typos,
1003
+ // and both parsers are pinned to the same rule by test.
1004
+ const bin = process.env.SHIPGATE_BIN || 'shipgate';
1005
+ const args = ['policy', '--mode', action];
1006
+ if (durationToken) args.push('--until', durationToken);
1007
+ const run = spawnSync(bin, args, {
1008
+ encoding: 'utf8',
1009
+ timeout: 15000,
1010
+ shell: process.platform === 'win32',
1011
+ });
1012
+ if (run.error || run.status !== 0) {
1013
+ const manual = [bin, ...args].join(' ');
1014
+ const detail = run.error
1015
+ ? run.error.code === 'ENOENT'
1016
+ ? `找不到 ${bin}(PATH 里没有 ShipGate CLI)。`
1017
+ : `调用 ${bin} 失败:${run.error.message}`
1018
+ : (run.stderr || run.stdout || `退出码 ${run.status}`).trim();
1019
+ notify(`${detail}\n模式没有被改变。手工执行:\n ${manual}`, 'error');
1019
1020
  return;
1020
1021
  }
1022
+ const reloadError = reloadPolicy();
1021
1023
  // A fresh global decision outranks a stale session override; leaving it
1022
1024
  // in place would make this command look like it did nothing.
1023
1025
  state.destructiveMode = null;
1026
+ if (reloadError) {
1027
+ notify(`真源已写入,但本会话重读失败:${reloadError}\n重启 pi 后生效。`, 'warn');
1028
+ return;
1029
+ }
1030
+ const m = modeState();
1024
1031
  const expiry =
1025
- action === 'bypass' && durationMs
1026
- ? `,${formatDurationMs(durationMs)} 后自动回 enforce`
1027
- : action === 'bypass'
1032
+ m.globalMode === 'bypass'
1033
+ ? m.remaining === null
1028
1034
  ? ',不过期'
1029
- : '';
1035
+ : `,剩 ${formatDurationMs(m.remaining)}`
1036
+ : '';
1037
+ const summary = (run.stdout || '').trim();
1030
1038
  notify(
1031
- action === 'bypass'
1032
- ? `破坏性命令已切到 BYPASS${expiry}(写入 ${read.file})。\n红线仍然拦;图谱/思考/契约/AI4S/密钥/越界写入等其他规则不受影响。\n收回:/gate mode enforce\n\n${modeHelp}`
1033
- : `破坏性命令已切到 ENFORCE(写入 ${read.file}),授权档位恢复生效。\n\n${modeHelp}`,
1039
+ (action === 'bypass'
1040
+ ? `破坏性命令已切到 BYPASS${expiry}(真源 ~/.config/shipgate/gate-policy.json,已同步到本机 harness)。\n红线仍然拦;图谱/思考/契约/AI4S/密钥/越界写入等其他规则不受影响。\n收回:/gate mode enforce`
1041
+ : `破坏性命令已切到 ENFORCE(真源 ~/.config/shipgate/gate-policy.json,已同步到本机 harness),授权档位恢复生效。`) +
1042
+ (summary ? `\n\n${summary}` : '') +
1043
+ `\n\n${modeHelp}`,
1034
1044
  action === 'bypass' ? 'warn' : 'info',
1035
1045
  );
1036
1046
  return;
@@ -1528,7 +1528,7 @@ const gateOwnedVerdict = (path) => ({
1528
1528
  '删掉、移走或改写它,等于把全部规则——包括任何模式都不放行的红线——一起卸掉,',
1529
1529
  '下一次会话就什么都不剩了。',
1530
1530
  '',
1531
- '要更新门控:改 agent-config-bridge 仓库源码 → node --test → node bridge/cli.js apply。',
1531
+ '要更新门控:改 ShipGate 仓库 assets/gates/(门控源已迁出 bridge)→ node --test → node bin/shipgate.mjs install。',
1532
1532
  '确实要卸载或手工修复:请主人亲手在终端执行。',
1533
1533
  ].join('\n'),
1534
1534
  });
@@ -2095,30 +2095,86 @@ export const destructiveModeRemainingMs = (config, now = Date.now()) => {
2095
2095
  /**
2096
2096
  * Where the machine-local gate override lives.
2097
2097
  *
2098
- * The bridge writes this same file when it generates `policy.json`, so a grant
2099
- * made here survives `apply` (which regenerates `policy.json`) instead of being
2100
- * overwritten by it. Deliberately outside every repository: a permission is a
2098
+ * ShipGate owns this gate - the bridge stopped shipping it - so the override
2099
+ * sits beside the policy truth instead of in the bridge's old directory. One
2100
+ * configuration root per machine: a tier the operator cannot find is a tier
2101
+ * nobody audits. Deliberately outside every repository: a permission is a
2101
2102
  * property of the machine and its user, not of the code being worked on.
2102
2103
  */
2103
2104
  export const machineGateConfigPath = (home = null) => {
2105
+ const base = home ?? process.env.HOME ?? process.env.USERPROFILE ?? '';
2106
+ return base ? join(base, '.config', 'shipgate', 'machine-override.json') : null;
2107
+ };
2108
+
2109
+ /**
2110
+ * The pre-ShipGate override path, read-only fallback only.
2111
+ *
2112
+ * Machines that predate this gate kept their grants there. It is never a write
2113
+ * target again: a grant created today lands in `machineGateConfigPath()`. The
2114
+ * file may be deleted at any time - the gate then runs on the shipped policy.
2115
+ */
2116
+ export const legacyMachineOverridePath = (home = null) => {
2104
2117
  const base = home ?? process.env.HOME ?? process.env.USERPROFILE ?? '';
2105
2118
  return base ? join(base, '.config', 'agent-config-bridge', 'gate-policy.json') : null;
2106
2119
  };
2107
2120
 
2108
2121
  /**
2109
- * The machine-local override as written, or null when absent or unparsable.
2122
+ * The only override keys the gate accepts from disk.
2110
2123
  *
2111
- * One reader for the file: `applyMachineOverride` merges it, and
2112
- * `machineProtectedListProblems` reports what the merge had to drop.
2124
+ * `destructive_mode` is deliberately absent. One hand-edited `bypass` with
2125
+ * `destructive_mode_until: 0` used to outrank the policy truth forever (the
2126
+ * merge is `{ ...policy.config, ...override }`) while `doctor` only reported
2127
+ * "a second policy file", so nothing on the surface said the gate had stopped
2128
+ * enforcing. The mode therefore has exactly one source: `gate-policy.json`,
2129
+ * reached through `shipgate policy --mode`. Grants and the protected list stay
2130
+ * overridable - those are per-machine facts, not a global policy decision.
2113
2131
  */
2114
- const readMachineOverride = (home = null) => {
2115
- const file = machineGateConfigPath(home);
2116
- if (!file) return null;
2132
+ const OVERRIDE_ALLOWED_KEYS = ['destructive_grants', 'protected_worktrees'];
2133
+
2134
+ const sanitizeOverride = (doc) => {
2135
+ const config = doc?.config;
2136
+ if (!config || typeof config !== 'object' || Array.isArray(config)) return null;
2137
+ const kept = {};
2138
+ for (const key of OVERRIDE_ALLOWED_KEYS) {
2139
+ if (config[key] !== undefined) kept[key] = config[key];
2140
+ }
2141
+ return Object.keys(kept).length > 0 ? { config: kept } : null;
2142
+ };
2143
+
2144
+ /**
2145
+ * Read one override file. `undefined` = no file, `null` = file without usable
2146
+ * keys, object = usable override. The distinction matters: an existing file
2147
+ * that clears the grants must win over a legacy file that still has them.
2148
+ */
2149
+ const readOneOverride = (file) => {
2150
+ if (!file) return undefined;
2151
+ let raw;
2152
+ try {
2153
+ raw = readFileSync(file, 'utf8');
2154
+ } catch {
2155
+ return undefined;
2156
+ }
2157
+ let parsed = null;
2117
2158
  try {
2118
- return JSON.parse(readFileSync(file, 'utf8'));
2159
+ parsed = JSON.parse(raw);
2119
2160
  } catch {
2120
2161
  return null;
2121
2162
  }
2163
+ return sanitizeOverride(parsed);
2164
+ };
2165
+
2166
+ /**
2167
+ * The machine-local override as written, or null when absent or unparsable.
2168
+ *
2169
+ * One reader for the file: `applyMachineOverride` merges it, and
2170
+ * `machineProtectedListProblems` reports what the merge had to drop. The new
2171
+ * path wins whenever it exists; the legacy path is read only when the new file
2172
+ * is missing, so an untouched machine keeps its grants through the upgrade.
2173
+ */
2174
+ const readMachineOverride = (home = null) => {
2175
+ const fresh = readOneOverride(machineGateConfigPath(home));
2176
+ if (fresh !== undefined) return fresh;
2177
+ return readOneOverride(legacyMachineOverridePath(home)) ?? null;
2122
2178
  };
2123
2179
 
2124
2180
  /**
@@ -2170,8 +2226,13 @@ export const applyMachineOverride = (policy, home = null) => {
2170
2226
  config.destructive_mode = normalizeDestructiveMode(config.destructive_mode);
2171
2227
  config.destructive_mode_until = normalizeDestructiveModeUntil(config.destructive_mode_until);
2172
2228
  // The protected-worktree list lives in this same file. It is a red line, so a
2173
- // malformed value may not reach the classifier raw.
2174
- config.protected_worktrees = normalizeProtectedWorktrees(config.protected_worktrees);
2229
+ // malformed value may not reach the classifier raw. Red lines only ever grow:
2230
+ // an override may ADD a protected tree, never drop one the policy declared
2231
+ // (`mergePolicy` unions them at install time; doing it again here keeps the
2232
+ // live gate from being weaker than the installed document).
2233
+ const policyRoots = normalizeProtectedWorktrees(policy.config?.protected_worktrees);
2234
+ const overrideRoots = normalizeProtectedWorktrees(config.protected_worktrees);
2235
+ config.protected_worktrees = [...new Set([...policyRoots, ...overrideRoots])];
2175
2236
  return { ...policy, config };
2176
2237
  };
2177
2238
 
@@ -3525,7 +3586,7 @@ const CHECKS = {
3525
3586
  ' · 想带着改动去别处比对 → git diff > <补丁文件>,或另 git worktree add / clone 一份',
3526
3587
  ' · 确实要清这个工作区 → 停下来,请主人亲手在终端执行',
3527
3588
  '',
3528
- '受保护目录登记在 ~/.config/agent-config-bridge/gate-policy.json 的',
3589
+ '受保护目录登记在 ~/.config/shipgate/machine-override.json 的',
3529
3590
  'config.protected_worktrees,只能由主人修改;/gate list 可以看到生效清单。',
3530
3591
  ].join('\n'),
3531
3592
  };
@@ -3628,6 +3689,12 @@ const CHECKS = {
3628
3689
  const posix = String(p ?? '').replace(/\\/g, '/').toLowerCase();
3629
3690
  if (!posix) return false;
3630
3691
  return (
3692
+ posix.endsWith('/.config/shipgate/machine-override.json') ||
3693
+ // The truth source: writing the mode here is the same act as writing it
3694
+ // into an override, one step earlier. It must stay off-limits to tools
3695
+ // even though no rule reads the mode from the override any more - the
3696
+ // file a rule DOES read is the more valuable target, not the less.
3697
+ posix.endsWith('/.config/shipgate/gate-policy.json') ||
3631
3698
  posix.endsWith('/.config/agent-config-bridge/gate-policy.json') ||
3632
3699
  /\/extensions\/enforce-rules\/policy\.json$/.test(posix)
3633
3700
  );
@@ -3687,9 +3754,10 @@ const CHECKS = {
3687
3754
  '或受保护工作区清单(protected_worktrees)。',
3688
3755
  '三者只能由用户亲手改:',
3689
3756
  ' 1) 交互弹窗里选「本会话允许 <类别>」—— 只对当前会话有效;',
3690
- ' 2) 敲 /gate grant <类别> —— 持久(写机器本地 gate-policy.json);',
3757
+ ' 2) 敲 /gate grant <类别> —— 持久(写机器本地 machine-override.json 的授权档位);',
3691
3758
  ' 3) 敲 /gate deny <类别> —— 收紧;/gate list 查看当前档位;',
3692
- ' 4) 敲 /gate mode bypass|enforce [时长] [session] —— 切换门控模式。',
3759
+ ' 4) 敲 /gate mode bypass|enforce [时长] [session] —— 切换门控模式',
3760
+ ' (真源 ~/.config/shipgate/gate-policy.json,由 ShipGate CLI 写并同步到各 harness)。',
3693
3761
  '',
3694
3762
  '为什么不让 agent 写:如果 agent 能改授权表或模式开关,所有分级都变成装饰——',
3695
3763
  '它只要给自己 allow db-ddl 或 destructive_mode: bypass 就绕过了破坏性命令门控;',
package/docs/HARNESS.md CHANGED
@@ -133,6 +133,48 @@ shipgate install --with-auto-continue # 无轮数上限
133
133
 
134
134
  同时指定 → 退出码 2。目标已存在会先备份 `*.shipgate-bak.<日期>` 再覆盖。
135
135
 
136
+ ## 机器级 override(`/gate` 写哪里)
137
+
138
+ `/gate grant|ask|deny|reset <类别>` 与受保护工作区登记,写的是**一个**文件:
139
+
140
+ ```
141
+ ~/.config/shipgate/machine-override.json
142
+ ```
143
+
144
+ 它只接受两个键:
145
+
146
+ | 键 | 含义 |
147
+ |---|---|
148
+ | `config.destructive_grants` | 六类破坏性操作的持久档位(allow / confirm / deny) |
149
+ | `config.protected_worktrees` | 额外登记的受保护工作区(**只增不减**:能加,不能删真源里的) |
150
+
151
+ `destructive_mode` **不接受**。模式(enforce / bypass)的唯一真源是 `~/.config/shipgate/gate-policy.json`,只能通过 `shipgate policy --mode` 改。历史上 override 能带 mode:一份 `bypass` + `until: 0` 就能永久盖住真源的 enforce,而 doctor 只报"第二份 policy"——运行时其实已经没闸了(见 `CHG-20261128-machine-override-single-source`)。
152
+
153
+ ### 模式开关怎么切(`/gate mode` → `shipgate policy --mode`)
154
+
155
+ `/gate mode bypass|enforce [时长]` 只是 `shipgate policy --mode` 的输入框封装:真正写的是真源
156
+ `~/.config/shipgate/gate-policy.json`,再由 `syncPolicyToHarnesses()` 投影到每个 harness 的 `policy.json`。
157
+ 只有一个写入者,所以“用户看到的模式”与“引擎读到的模式”不会分叉;pi 适配器在写完后立即重读自己的
158
+ `policy.json`(`reloadPolicy()`),本会话即生效,无需重开。
159
+
160
+ | 命令 | 落点 | 效果 |
161
+ |---|---|---|
162
+ | `/gate mode bypass` | `gate-policy.json` | 持久 bypass(`until = 0`,不过期) |
163
+ | `/gate mode bypass 30m` | 同上 | 30 分钟后自动回 enforce(`s/m/h/d`,裸数字 = 小时) |
164
+ | `/gate mode enforce` | 同上 | 立即收回,并把 `until` 清零 |
165
+ | `/gate mode bypass session` | 内存 | 仅本会话,不写盘 |
166
+
167
+ `shipgate policy` 展示的是**有效**模式:`until` 已过期时即使文件仍记 `bypass`,也显示
168
+ `enforce(bypass 已于 … 到期)`——展示与运行时读的是同一个判定(`policyModeView`)。
169
+
170
+ agent 不能写 `gate-policy.json`(`no-self-grant` 拦截);模式开关只能由主人敲 `/gate mode`
171
+ 或 `shipgate policy --mode`,与 grant 只能由 `/gate grant` 敲是同一条边界。
172
+
173
+ > 测试/演练请用 `SHIPGATE_STATE_DIR=<临时目录>` 把 CLI 指向一次性的 state 目录,
174
+ > 不要用测试去切真机的闸。
175
+
176
+ 旧路径 `~/.config/agent-config-bridge/gate-policy.json` 只在**新文件不存在时只读回退**(升级继承已有 grants),不再被写入,可随时删除。
177
+
136
178
  ## 遗留门控检测(doctor)
137
179
 
138
180
  `shipgate doctor` 会报告与 agent-config-bridge 并存导致的冲突,**只报告不自动删**:
@@ -140,7 +182,7 @@ shipgate install --with-auto-continue # 无轮数上限
140
182
  | code | 含义 | 处理 |
141
183
  |---|---|---|
142
184
  | `LEGACY_GATE_DUPLICATE` | pi 同时装了 `coding-gateways`(bridge) 与 `enforce-rules`(ShipGate) | 按提示停用其中一份 |
143
- | `LEGACY_POLICY_SOURCE` | 存在第二份 policy 真源 `~/.config/agent-config-bridge/gate-policy.json` | 统一到 `~/.config/shipgate/gate-policy.json` |
185
+ | `LEGACY_OVERRIDE_FILE` | 旧 override 文件仍在 `~/.config/agent-config-bridge/gate-policy.json`(**已停读**:其中的 `destructive_mode` 不再生效,grants 与受保护目录由新路径承接) | 可直接删除;按提示 `rm -f` 即可 |
144
186
  | `DSH_GATE_MISMOUNT` | dsh 的 cordis.patch 挂的不是 `enforce-rules` | 改挂接行指向 ShipGate 产物 |
145
187
 
146
188
  ## skill 根卫生(doctor)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shipgate-cli",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "ShipGate — the full-lifecycle gate chain for AI-written code: 27 dev skills, spec/quality/security/ship gates, hard gates, and one-command deployment across coding harnesses.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.mjs CHANGED
@@ -71,7 +71,8 @@ ${c.bold('硬门控(pi / dsh 类)')}
71
71
  shipgate policy 策略真源 + 各 harness 落地状态
72
72
  shipgate policy --add-protected <dir>
73
73
  shipgate policy --rm-protected <dir>
74
- shipgate policy --mode enforce|bypass
74
+ shipgate policy --mode enforce|bypass [--until 8h]
75
+ 写策略真源 → 同步到所有 harness;--until 只给 bypass
75
76
  shipgate policy --sync
76
77
 
77
78
  ${c.bold('受管与升级')}
@@ -110,14 +110,10 @@ function installPiExtension(ctx, name, { dryRun }) {
110
110
  }
111
111
 
112
112
  /**
113
- * Platform-correct move instruction. The operator's shell decides the syntax:
114
- * printing `mv` to a PowerShell user (or `Move-Item` to bash) turns a fix into a
115
- * second failure, which already happened once.
113
+ * Report-only: gate artefacts left by agent-config-bridge would load alongside
114
+ * ShipGate's bundle. Never deleted automatically — the operator gets the exact
115
+ * command and decides.
116
116
  */
117
- function moveCommand(from, to) {
118
- return process.platform === 'win32' ? `Move-Item "${from}" "${to}"` : `mv "${from}" "${to}"`;
119
- }
120
-
121
117
  function moveIntoDirCommand(from, dir) {
122
118
  return process.platform === 'win32'
123
119
  ? `New-Item -ItemType Directory -Force "${dir}" | Out-Null; Move-Item "${from}" "${dir}"`
@@ -144,18 +140,20 @@ export function reportLegacyGates(home) {
144
140
  command: moveIntoDirCommand(legacy.bridgePiGate, quarantineDir),
145
141
  });
146
142
  }
147
- if (legacy.bridgePolicy) {
148
- const shipMode = loadPolicy().config.destructive_mode;
149
- const sameMode = legacy.bridgePolicyMode === shipMode;
143
+ if (legacy.legacyOverride) {
144
+ // Not a "second truth": the live gate reads ShipGate's override file and
145
+ // drops `destructive_mode` from ANY override, so the mode written here
146
+ // cannot decide behaviour whichever order things load in. Clutter to
147
+ // delete, therefore info — and the old advice (rename to `.disabled`) was
148
+ // useless precisely because the file kept being read.
150
149
  findings.push({
151
- code: 'LEGACY_POLICY_SOURCE',
152
- // Same mode = no behavioural conflict, only clutter. Warning every run
153
- // trains the operator to ignore warnings.
154
- level: sameMode ? 'info' : 'warn',
155
- message: sameMode
156
- ? `bridge 的第二份 policy 仍在(${legacy.bridgePolicy},mode=${legacy.bridgePolicyMode} 与 ShipGate 相同,已不影响行为;仅建议清理)`
157
- : `第二份 policy 真源:${legacy.bridgePolicy}(${legacy.bridgePolicyMode}),ShipGate(${shipMode})—— 两者不一致时拦截行为取决于加载顺序`,
158
- command: moveCommand(legacy.bridgePolicy, `${legacy.bridgePolicy}.disabled`),
150
+ code: 'LEGACY_OVERRIDE_FILE',
151
+ level: 'info',
152
+ message: `旧 override 文件已停读:${legacy.legacyOverride}(其中的 destructive_mode=${legacy.legacyOverrideMode} 已不生效;grants 与受保护目录由 ~/.config/shipgate/machine-override.json 承接)。可删除。`,
153
+ command:
154
+ process.platform === 'win32'
155
+ ? `Remove-Item "${legacy.legacyOverride}"`
156
+ : `rm -f "${legacy.legacyOverride}"`,
159
157
  });
160
158
  }
161
159
  if (legacy.dshMounted.length > 0 && !legacy.dshMounted.includes('enforce-rules')) {
@@ -1,5 +1,15 @@
1
1
  import { c, log, table } from '../lib/log.mjs';
2
- import { addProtected, gateStatus, loadPolicy, removeProtected, setMode, syncPolicyToHarnesses } from '../lib/gate.mjs';
2
+ import { formatDurationMs, parseDurationMs } from '../lib/duration.mjs';
3
+ import {
4
+ addProtected,
5
+ gateStatus,
6
+ globalPolicyPath,
7
+ loadPolicy,
8
+ policyModeView,
9
+ removeProtected,
10
+ setMode,
11
+ syncPolicyToHarnesses,
12
+ } from '../lib/gate.mjs';
3
13
  import { allHarnesses, detected, resolveHarness } from '../harness/index.mjs';
4
14
 
5
15
  function gatedHarnesses(cfg) {
@@ -26,30 +36,69 @@ export function policyCommand(ctx) {
26
36
  }
27
37
 
28
38
  if (flags.mode) {
29
- const policy = setMode(String(flags.mode));
30
- log.ok(`destructive_mode = ${policy.config.destructive_mode}`);
39
+ const mode = String(flags.mode);
40
+ if (!['enforce', 'bypass'].includes(mode)) {
41
+ log.err(`--mode 只能是 enforce 或 bypass,收到:${mode}`);
42
+ return 2;
43
+ }
44
+ if (flags.until !== undefined && mode !== 'bypass') {
45
+ // A deadline on enforce is a contradiction: enforce is already the
46
+ // immediate state, and the leftover timestamp would shorten the next
47
+ // bypass the user asks for.
48
+ log.err('--until 只用于 --mode bypass;enforce 不需要时长。');
49
+ return 2;
50
+ }
51
+ const durationMs = flags.until === undefined ? 0 : parseDurationMs(flags.until);
52
+ if (durationMs === null) {
53
+ log.err(`看不懂时长「${flags.until}」。用 90s / 30m / 8h / 2d,或裸数字(= 小时)。`);
54
+ return 2;
55
+ }
56
+ let policy;
57
+ try {
58
+ policy = setMode(mode, { durationMs });
59
+ } catch (error) {
60
+ log.err(error.message);
61
+ return 2;
62
+ }
63
+ const view = policyModeView(policy);
64
+ const expiry =
65
+ view.mode === 'bypass'
66
+ ? view.remainingMs === null
67
+ ? '(不过期)'
68
+ : `(剩 ${formatDurationMs(view.remainingMs)},直到 ${new Date(view.until).toISOString()})`
69
+ : '';
70
+ log.ok(`destructive_mode = ${view.mode}${expiry} ← ${globalPolicyPath()}`);
31
71
  return syncAll(ctx);
32
72
  }
33
73
 
34
74
  if (flags.sync) return syncAll(ctx);
35
75
 
36
76
  const policy = loadPolicy();
77
+ const view = policyModeView(policy);
78
+ // The raw field and the effective mode disagree exactly when a bounded
79
+ // bypass has expired. Printing the field alone is how the switch looked
80
+ // broken; say both halves when they differ.
81
+ const source = view.expired
82
+ ? `enforce(bypass 已于 ${new Date(view.until).toISOString()} 到期;文件仍记 bypass,要重开请 policy --mode bypass)`
83
+ : view.mode === 'bypass'
84
+ ? `bypass${view.remainingMs === null ? '(不过期)' : `(剩 ${formatDurationMs(view.remainingMs)})`}`
85
+ : 'enforce';
37
86
  const rows = gatedHarnesses(ctx.cfg).map((harness) => {
38
87
  const status = gateStatus(harness);
39
88
  return [harness.id, status.installed ? 'installed' : 'missing', status.mode ?? '-', String(status.protected ?? 0), harness.gateDest];
40
89
  });
41
90
 
42
91
  if (ctx.flags.json) {
43
- log.plain(JSON.stringify({ policy, harnesses: rows }, null, 2));
92
+ log.plain(JSON.stringify({ policy, mode_view: view, harnesses: rows }, null, 2));
44
93
  return 0;
45
94
  }
46
95
 
47
- log.title(`策略真源:${policy.config.destructive_mode} · 受保护工作区 ${policy.config.protected_worktrees.length} 条`);
96
+ log.title(`策略真源:${source} · 受保护工作区 ${policy.config.protected_worktrees.length} 条`);
48
97
  for (const p of policy.config.protected_worktrees) log.info(` · ${p}`);
49
98
  log.title('硬门控落地');
50
99
  if (rows.length === 0) log.warn('没有任何 harness 配置了 gate(只有 pi/dsh 类需要)');
51
100
  else log.plain(table(rows, ['harness', 'gate', 'mode', 'protected', '路径']));
52
- log.info(c.dim('用法:shipgate policy --add-protected <dir> | --rm-protected <dir> | --mode enforce|bypass | --sync'));
101
+ log.info(c.dim('用法:shipgate policy --add-protected <dir> | --rm-protected <dir> | --mode enforce|bypass [--until 8h] | --sync'));
53
102
  return 0;
54
103
  }
55
104
 
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The one duration grammar the destructive-mode switch accepts:
3
+ * `90s` / `30m` / `8h` / `2d`, or a bare number (= hours).
4
+ *
5
+ * The pi adapter has its own pre-check (`parseGateDurationMs` in
6
+ * `assets/gates/pi/index.js`) because `/gate mode` must refuse a typo before it
7
+ * spawns anything. Both implementations are kept character-for-character equal
8
+ * on purpose: the adapter validates, this module is what the CLI actually
9
+ * writes. If they drifted, a user typing `8h` would get a different expiry than
10
+ * the one they asked for - and an expiry nobody can predict is worse than no
11
+ * expiry at all (CHG-20261129-gate-mode-true-source).
12
+ *
13
+ * Anything unparseable returns `null`; callers must refuse rather than guess.
14
+ */
15
+ const UNITS = { s: 1000, m: 60000, h: 3600000, d: 86400000 };
16
+
17
+ export function parseDurationMs(text) {
18
+ const m = /^(\d+(?:\.\d+)?)\s*(s|m|h|d)?$/i.exec(String(text ?? '').trim());
19
+ if (!m) return null;
20
+ const n = Number(m[1]);
21
+ if (!Number.isFinite(n) || n <= 0) return null;
22
+ const unit = (m[2] ?? 'h').toLowerCase();
23
+ return Math.round(n * UNITS[unit]);
24
+ }
25
+
26
+ /** Human form of a duration, for the policy banner and the `/gate mode` reply. */
27
+ export function formatDurationMs(ms) {
28
+ const total = Math.max(0, Math.round(Number(ms) / 1000));
29
+ if (total >= 86400) {
30
+ const d = Math.floor(total / 86400);
31
+ const h = Math.floor((total % 86400) / 3600);
32
+ return h > 0 ? `${d}d${h}h` : `${d}d`;
33
+ }
34
+ if (total >= 3600) {
35
+ const h = Math.floor(total / 3600);
36
+ const m = Math.floor((total % 3600) / 60);
37
+ return m > 0 ? `${h}h${m}m` : `${h}h`;
38
+ }
39
+ if (total >= 60) return `${Math.floor(total / 60)}m`;
40
+ return `${Math.max(1, total)}s`;
41
+ }
package/src/lib/gate.mjs CHANGED
@@ -24,19 +24,19 @@ export function gatesSource() {
24
24
  * Single source of truth for gate policy. Harness policy.json files are
25
25
  * projections of this file, so `policy --sync` can always rebuild them.
26
26
  */
27
- export function loadPolicy() {
28
- const text = readIfExists(globalPolicyPath());
27
+ export function loadPolicy(dir = stateDir()) {
28
+ const text = readIfExists(path.join(dir, 'gate-policy.json'));
29
29
  if (text === null) return structuredClone(DEFAULT_POLICY);
30
30
  try {
31
31
  const parsed = JSON.parse(text);
32
32
  return { ...structuredClone(DEFAULT_POLICY), ...parsed, config: { ...DEFAULT_POLICY.config, ...(parsed.config ?? {}) } };
33
33
  } catch (error) {
34
- throw new Error(`gate-policy.json 损坏,请检查 ${globalPolicyPath()}:${error.message}`);
34
+ throw new Error(`gate-policy.json 损坏,请检查 ${path.join(dir, 'gate-policy.json')}:${error.message}`);
35
35
  }
36
36
  }
37
37
 
38
- export function savePolicy(policy) {
39
- writeText(globalPolicyPath(), JSON.stringify(policy, null, 2) + '\n');
38
+ export function savePolicy(policy, dir = stateDir()) {
39
+ writeText(path.join(dir, 'gate-policy.json'), JSON.stringify(policy, null, 2) + '\n');
40
40
  return policy;
41
41
  }
42
42
 
@@ -60,14 +60,45 @@ export function removeProtected(dir) {
60
60
  return savePolicy(policy);
61
61
  }
62
62
 
63
- export function setMode(mode) {
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() } = {}) {
64
71
  if (!['enforce', 'bypass'].includes(mode)) {
65
72
  throw new Error(`destructive_mode 只能是 enforce 或 bypass,收到:${mode}`);
66
73
  }
67
- const policy = loadPolicy();
74
+ if (mode === 'enforce' && durationMs > 0) {
75
+ throw new Error('enforce 不接受时长:带时长的是有界 bypass,enforce 只会立刻生效。');
76
+ }
77
+ const policy = loadPolicy(dir);
68
78
  policy.config.destructive_mode = mode;
69
- policy.config.destructive_mode_until = 0;
70
- return savePolicy(policy);
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
+ };
71
102
  }
72
103
 
73
104
  /**
@@ -208,10 +239,14 @@ export function gateStatus(harness) {
208
239
  if (!harness.gateDest) return { installed: false, reason: 'harness 无 gate 配置' };
209
240
  if (!exists(harness.gateDest)) return { installed: false, reason: '目录不存在' };
210
241
  const policy = readJson(path.join(harness.gateDest, 'policy.json'));
242
+ const view = policyModeView(policy ?? {});
211
243
  return {
212
244
  installed: exists(path.join(harness.gateDest, 'policy.js')) && exists(path.join(harness.gateDest, 'classifier.js')),
213
245
  dir: harness.gateDest,
214
- mode: policy?.config?.destructive_mode ?? 'unknown',
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,
215
250
  protected: policy?.config?.protected_worktrees?.length ?? 0,
216
251
  };
217
252
  }
@@ -269,10 +304,14 @@ export function detectLegacyGates({ home = HOME } = {}) {
269
304
  // holds a real gate bundle; a plain provider extension must not match.
270
305
  const rivalGates = exists(shipGatePi) ? otherGateBundles(piExtDir, 'enforce-rules') : [];
271
306
  const dshGate = path.join(home, '.dsh', 'plugins', 'agent-config-gates');
272
- const bridgePolicy = path.join(home, '.config', 'agent-config-bridge', 'gate-policy.json');
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');
273
312
 
274
- const bridgePolicyMode = (() => {
275
- const parsed = readJson(bridgePolicy);
313
+ const legacyOverrideMode = (() => {
314
+ const parsed = readJson(legacyOverride);
276
315
  return parsed && !parsed.__malformed ? (parsed.config?.destructive_mode ?? 'unknown') : 'unknown';
277
316
  })();
278
317
 
@@ -281,8 +320,10 @@ export function detectLegacyGates({ home = HOME } = {}) {
281
320
  rivalGates,
282
321
  shipGatePi: exists(shipGatePi) ? shipGatePi : null,
283
322
  bridgeDshGate: exists(dshGate) && isGateBundle(dshGate) ? dshGate : null,
284
- bridgePolicy: exists(bridgePolicy) ? bridgePolicy : null,
285
- bridgePolicyMode,
323
+ bridgePolicy: exists(legacyOverride) ? legacyOverride : null,
324
+ legacyOverride: exists(legacyOverride) ? legacyOverride : null,
325
+ bridgePolicyMode: legacyOverrideMode,
326
+ legacyOverrideMode,
286
327
  dshMounted: scanDshMounts(path.join(home, '.dsh', 'profiles')),
287
328
  };
288
329
  }
package/src/lib/state.mjs CHANGED
@@ -2,8 +2,17 @@ import path from 'node:path';
2
2
  import { HOME } from './cfg.mjs';
3
3
  import { readIfExists, writeText } from './fsx.mjs';
4
4
 
5
+ /**
6
+ * ShipGate's own configuration root.
7
+ *
8
+ * `SHIPGATE_STATE_DIR` exists so a test or a drill can point the CLI at a
9
+ * throwaway directory instead of the live policy. Without it, a test of
10
+ * `policy --mode` would switch the real gate - the one thing a test must never
11
+ * do. Unset means the normal per-user location.
12
+ */
5
13
  export function stateDir() {
6
- return path.join(HOME, '.config', 'shipgate');
14
+ const override = process.env.SHIPGATE_STATE_DIR;
15
+ return override ? path.resolve(override) : path.join(HOME, '.config', 'shipgate');
7
16
  }
8
17
 
9
18
  export function manifestPath() {