huaweicloud-devkit 2.0.0-next.5 → 2.0.0-next.6

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 (40) hide show
  1. package/README.md +1 -1
  2. package/integrations/opencode/commands/huaweicloud-doctor.md +1 -1
  3. package/integrations/opencode/hooks/safety-gate.js +235 -0
  4. package/package.json +1 -1
  5. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -1
  6. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
  7. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
  8. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
  9. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
  10. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +29 -4
  11. package/plugins/huaweicloud-core/dist/agents/opencode.js +55 -14
  12. package/plugins/huaweicloud-core/dist/approval-gate.js +23 -5
  13. package/plugins/huaweicloud-core/dist/doctor-payload.js +29 -0
  14. package/plugins/huaweicloud-core/dist/lib/opencode-permission-seam.js +51 -20
  15. package/plugins/huaweicloud-core/dist/mcp-server.js +85 -8
  16. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  17. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +5 -1
  18. package/plugins/huaweicloud-core/dist/payload-placement.js +8 -0
  19. package/plugins/huaweicloud-core/dist/safety/classify-text.js +10 -0
  20. package/plugins/huaweicloud-core/dist/safety/policy.js +12 -0
  21. package/plugins/huaweicloud-core/dist/safety/protected-payload.js +93 -0
  22. package/plugins/huaweicloud-core/dist/safety-integrity.js +122 -0
  23. package/plugins/huaweicloud-core/dist/setup-cli.js +8 -1
  24. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +44 -1
  25. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +61 -1
  26. package/plugins/huaweicloud-core/openclaw.plugin.json +2 -2
  27. package/plugins/huaweicloud-core/safety/policy.json +5 -0
  28. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +1 -1
  29. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +33 -3
  30. package/plugins/huaweicloud-core/src/agents/opencode.ts +66 -15
  31. package/plugins/huaweicloud-core/src/approval-gate.ts +29 -4
  32. package/plugins/huaweicloud-core/src/doctor-payload.ts +40 -2
  33. package/plugins/huaweicloud-core/src/lib/opencode-permission-seam.ts +60 -19
  34. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +7 -1
  35. package/plugins/huaweicloud-core/src/payload-placement.ts +8 -0
  36. package/plugins/huaweicloud-core/src/safety/classify-text.ts +10 -0
  37. package/plugins/huaweicloud-core/src/safety/policy.ts +13 -0
  38. package/plugins/huaweicloud-core/src/safety/protected-payload.ts +97 -0
  39. package/plugins/huaweicloud-core/src/safety-integrity.ts +132 -0
  40. package/plugins/huaweicloud-core/src/setup-cli.ts +8 -0
@@ -34,9 +34,11 @@ import {
34
34
  openCodeSeamGate,
35
35
  openCodeSeamGlobs,
36
36
  openCodeAskGate,
37
+ openCodeSafetyGate,
37
38
  } from './opencode-config.ts';
38
39
  import { readPermissionRules, readPermissionRulesV1, type RosterRuleState } from '../lib/opencode-ask-rule.ts';
39
40
  import { scanSavedAllowRows } from '../lib/opencode-saved-perms.ts';
41
+ import { payloadEditDenyGlobs } from '../lib/opencode-permission-seam.ts';
40
42
  import type { DoctorReporter } from '../doctor-report.ts';
41
43
  import { asRecord } from '../lib/as-record.ts';
42
44
 
@@ -204,23 +206,27 @@ function savedAllowStoreCheck(ctx: DoctorReporter): void {
204
206
 
205
207
  // Doctor: the skills-tree permission seam check — OpenCode installs only
206
208
  // (the seam is the installer's zero-prompt path for direct skill reads on
207
- // that harness). Verifies the two keys and their values, honoring the
208
- // ownership contract: a user-owned value on a devkit glob is reported as
209
- // kept, not broken; a below-floor or absent opencode is a SKIP, never a
210
- // FAIL.
209
+ // that harness). Verifies the keys and their values over BOTH glob classes,
210
+ // honoring the ownership contract: a user-owned value on a devkit glob is
211
+ // reported as kept, not broken; a below-floor or absent opencode is a SKIP,
212
+ // never a FAIL.
211
213
  export function opencodeDoctorSeam(ctx: DoctorReporter): void {
212
214
  if (openCodeSeamGate() === 'off') {
213
215
  ctx.skip('Skills-tree permission seam (opencode not verifiably at or above the measured permission floor)');
214
216
  return;
215
217
  }
216
- // Per-glob evaluation, matching the installer's per-section/per-glob
218
+ // Per-glob, two-class evaluation, matching the installer's per-section
217
219
  // contract exactly: user-owned globs (any non-devkit value) are reported
218
220
  // as kept, missing globs as healable — one user-owned glob must never
219
- // mask a missing edit deny. Configs the installer itself refuses to
221
+ // mask a healable gap. The edit-only class (the payload root — the
222
+ // classifier the in-process gate imports) requires just the edit deny:
223
+ // the external allow is deliberately absent there, so requiring it would
224
+ // fail every healthy install. Configs the installer itself refuses to
220
225
  // touch (scalar-shaped permission, unparseable file — the parse-fail
221
226
  // skip is the install path's ONLY skip) get a SKIP with the manual
222
227
  // pointer, never a FAIL whose re-run-install remediation cannot succeed.
223
228
  const globs = openCodeSeamGlobs(opencodePluginsDir());
229
+ const editOnlyGlobs = payloadEditDenyGlobs(opencodePluginsDir());
224
230
  let cfg: Record<string, unknown> | null;
225
231
  try {
226
232
  cfg = asRecord(JSON.parse(readFileSync(opencodeConfigFile(), 'utf8')));
@@ -240,28 +246,52 @@ export function opencodeDoctorSeam(ctx: DoctorReporter): void {
240
246
  const permRecord = asRecord(permission);
241
247
  const ext = asRecord(permRecord.external_directory);
242
248
  const editRules = asRecord(permRecord.edit);
243
- const kept = globs.filter((g) => (g in ext && ext[g] !== 'allow') || (g in editRules && editRules[g] !== 'deny'));
244
- const missing = globs.filter((g) => ext[g] !== 'allow' || editRules[g] !== 'deny');
245
- if (missing.length === 0) {
246
- ctx.check('Skills-tree permission seam (allow + edit deny)', true, '');
247
- } else if (kept.length === 0) {
249
+ const kept =
250
+ globs.filter((g) => (g in ext && ext[g] !== 'allow') || (g in editRules && editRules[g] !== 'deny')).length +
251
+ editOnlyGlobs.filter((g) => g in editRules && editRules[g] !== 'deny').length;
252
+ const missing =
253
+ globs.filter((g) => ext[g] !== 'allow' || editRules[g] !== 'deny').length +
254
+ editOnlyGlobs.filter((g) => editRules[g] !== 'deny').length;
255
+ const LABEL = 'Skills-tree permission seam (allow + edit deny; payload edit deny)';
256
+ if (missing === 0) {
257
+ ctx.check(LABEL, true, '');
258
+ } else if (kept === 0) {
248
259
  ctx.check(
249
- 'Skills-tree permission seam (allow + edit deny)',
260
+ LABEL,
250
261
  false,
251
- 'Run: npx huaweicloud-devkit install (writes the missing skills-tree rules; see README, Harness permission notes)',
262
+ 'Run: npx huaweicloud-devkit install (writes the missing seam rules; see README, Harness permission notes)',
252
263
  );
253
264
  } else {
254
265
  ctx.check(
255
- 'Skills-tree permission seam (allow + edit deny)',
266
+ LABEL,
256
267
  false,
257
- `${missing.length} rule(s) missing (re-run: npx huaweicloud-devkit install); ${kept.length} user-owned glob(s) kept as-is (see README, Harness permission notes)`,
268
+ `${missing} rule(s) missing (re-run: npx huaweicloud-devkit install); ${kept} user-owned glob(s) kept as-is (see README, Harness permission notes)`,
258
269
  );
259
270
  }
260
271
  }
261
272
 
273
+ // Doctor: the shell safety gate — OpenCode installs only (the evaluate-hook
274
+ // adapter is the opencode ≥ 2.0 in-process deny face for shell commands).
275
+ // A below-floor, absent, or unparsable opencode is a SKIP, never a FAIL
276
+ // (the adapter has no surface to register on there); a verifiably ≥ 2.0
277
+ // opencode with a missing adapter file is the FAIL install heals.
278
+ export function opencodeDoctorSafetyGate(ctx: DoctorReporter): void {
279
+ if (openCodeSafetyGate() === 'off') {
280
+ ctx.skip('Shell safety gate (opencode not verifiably at or above 2.0.0)');
281
+ return;
282
+ }
283
+ const gateFile = join(configRoot('opencode'), 'plugins', 'safety-gate.js');
284
+ ctx.check(
285
+ 'Shell safety gate (evaluate-hook adapter)',
286
+ existsSync(gateFile),
287
+ 'Run: npx huaweicloud-devkit install --target opencode',
288
+ );
289
+ }
290
+
262
291
  export async function deployOpenCode(mode: DeployMode): Promise<void> {
263
292
  const commandsSrc = join(PACKAGE_ROOT, 'integrations', 'opencode', 'commands');
264
293
  const pluginSrc = join(PACKAGE_ROOT, 'integrations', 'opencode', 'hooks', 'skill-tracker.js');
294
+ const gateSrc = join(PACKAGE_ROOT, 'integrations', 'opencode', 'hooks', 'safety-gate.js');
265
295
  const pluginDest = opencodePluginsDir();
266
296
 
267
297
  copyDir(commandsSrc, opencodeCommandsDir());
@@ -274,6 +304,19 @@ export async function deployOpenCode(mode: DeployMode): Promise<void> {
274
304
  mkdirSync(opcPlugins, { recursive: true });
275
305
  copyFileSync(pluginSrc, join(opcPlugins, 'skill-tracker.js'));
276
306
  console.log(` Plugin${deployWord(mode)} -> ${opcPlugins}`);
307
+ const gateFile = join(opcPlugins, 'safety-gate.js');
308
+ if (openCodeSafetyGate() === 'on') {
309
+ copyFileSync(gateSrc, gateFile);
310
+ console.log(` Safety gate${deployWord(mode)} -> ${opcPlugins}`);
311
+ } else {
312
+ // Drift heal, same doctrine as the ask-rule migration: an opencode that
313
+ // downgraded or vanished since the last install must not keep the file
314
+ // (a below-floor host has no evaluate hook to run it on).
315
+ removeIfExists(gateFile);
316
+ console.log(
317
+ ' \x1b[33m[INFO]\x1b[0m opencode not verifiably at or above 2.0.0 — skipping the shell safety-gate plugin; a below-floor host has no evaluate hook to gate the Bash face on.',
318
+ );
319
+ }
277
320
  updateOpenCodeConfig(pluginDest);
278
321
 
279
322
  installRuntimeDeps(pluginDest);
@@ -292,6 +335,12 @@ export function uninstallOpenCode(removeOwnedSkills: (dir: string) => number): v
292
335
  console.log(' Removed plugin');
293
336
  }
294
337
 
338
+ const gateFile = join(configRoot('opencode'), 'plugins', 'safety-gate.js');
339
+ if (existsSync(gateFile)) {
340
+ removeIfExists(gateFile);
341
+ console.log(' Removed safety-gate plugin');
342
+ }
343
+
295
344
  if (removeIfExists(opencodePluginsDir())) {
296
345
  console.log(' Removed MCP server and safety policy');
297
346
  }
@@ -300,5 +349,7 @@ export function uninstallOpenCode(removeOwnedSkills: (dir: string) => number): v
300
349
 
301
350
  export function opencodeStatus(): void {
302
351
  payloadStatusLines(opencodePluginsDir());
352
+ const gateInstalled = existsSync(join(configRoot('opencode'), 'plugins', 'safety-gate.js'));
353
+ console.log(` Shell safety gate: ${gateInstalled ? '\x1b[32mInstalled\x1b[0m' : '\x1b[31mNot installed\x1b[0m'}`);
303
354
  printMcpConfigStatus(opencodeConfigFile(), 'mcp');
304
355
  }
@@ -86,6 +86,21 @@ export const NO_SESSION_SEAM_ERROR =
86
86
  const GRANT_REQUIRED_NEXT_STEP =
87
87
  'Ask the user to run "npx huaweicloud-devkit approve <this approvalToken>" in their own terminal, then retry this exact call.';
88
88
 
89
+ // F-APV-1: every CONFIRM_TOKEN_* rejection spells its way out — the ask
90
+ // envelope and the mint envelope already carry nextStep, and these close the
91
+ // gap so the model never has to reverse-engineer the approval flow from
92
+ // tool descriptions. Splitting NOT_FOUND into MISSING vs INVALID is a
93
+ // contract change held for its own pass; this keeps the pinned codes and
94
+ // only adds the guidance. Exported for the tests that pin the envelopes.
95
+ export const PLAN_FACE_TOKEN_MISSING_NEXT_STEP =
96
+ 'This run call requires an approvalToken minted by the plan face. Call huaweicloud_plan_cli_command with the same args first — its USER_CONFIRMATION_REQUIRED envelope carries the fresh approvalToken; retry this call with it.';
97
+
98
+ export const CONFIRM_TOKEN_UNKNOWN_NEXT_STEP =
99
+ 'This approvalToken was never minted in this process — malformed, or dropped by a server restart (tokens are process-scoped and never persisted). Re-run the plan call to mint a fresh approvalToken, then retry this call with it.';
100
+
101
+ export const CONFIRM_TOKEN_EXPIRED_NEXT_STEP =
102
+ 'This approvalToken passed its 5-minute TTL. Re-run the plan call to mint a fresh approvalToken and have the user approve it promptly, then retry this call with it.';
103
+
89
104
  // The command-forward anchor (the operator-approved display field): a call
90
105
  // that carries the tool's `command` string must spell the exact line its args
91
106
  // execute, so the harness popup's first line is the command the user is
@@ -951,7 +966,9 @@ export async function runApprovalGate(
951
966
  // classified nothing on a tokenless call, and the plan face's own hook
952
967
  // deny already covers the credential class at plan time.
953
968
  if (spec.tokenSource === 'plan-face') {
954
- return { envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND' } };
969
+ return {
970
+ envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND', nextStep: PLAN_FACE_TOKEN_MISSING_NEXT_STEP },
971
+ };
955
972
  }
956
973
  // Gate-source mint face (PR-3 registrations; ApprovalCoreMint's
957
974
  // classify-before-mint). BOTH floors sit before the mint for the same
@@ -991,13 +1008,17 @@ export async function runApprovalGate(
991
1008
  return { envelope: { status: 'ok', outcome: 'already_processed' } };
992
1009
  }
993
1010
  if (inspection.state === 'expired') {
994
- return { envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED' } };
1011
+ return {
1012
+ envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED', nextStep: CONFIRM_TOKEN_EXPIRED_NEXT_STEP },
1013
+ };
995
1014
  }
996
1015
  if (inspection.state === 'not_found') {
997
1016
  // A token that was never created (typo / unknown / pruned beyond the
998
1017
  // tombstone window) is still a rejection, but carries no expired or
999
1018
  // already semantics — a distinct code so clients can tell them apart.
1000
- return { envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND' } };
1019
+ return {
1020
+ envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND', nextStep: CONFIRM_TOKEN_UNKNOWN_NEXT_STEP },
1021
+ };
1001
1022
  }
1002
1023
 
1003
1024
  // Credential floor before the consume, so the refusal burns nothing and
@@ -1019,7 +1040,11 @@ export async function runApprovalGate(
1019
1040
  // two reads. Classify via re-inspect, never a misleading success and
1020
1041
  // never a false not_found.
1021
1042
  const recheck = inspectApprovalToken(token);
1022
- if (recheck.state === 'expired') return { envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED' } };
1043
+ if (recheck.state === 'expired') {
1044
+ return {
1045
+ envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED', nextStep: CONFIRM_TOKEN_EXPIRED_NEXT_STEP },
1046
+ };
1047
+ }
1023
1048
  return { envelope: { status: 'ok', outcome: 'already_processed' } };
1024
1049
  }
1025
1050
 
@@ -12,6 +12,7 @@ import { join } from 'node:path';
12
12
  import type { DoctorReporter } from './doctor-report.ts';
13
13
  import { nativeFreshnessChecks } from './doctor-native.ts';
14
14
  import { mcpServerInstalled, serverSkillDirNames } from './install-payload.ts';
15
+ import { verifyIntegrity } from './safety-integrity.ts';
15
16
 
16
17
  // The structural slice of a PAYLOAD_TARGETS row the doctor sections consume.
17
18
  export interface PayloadDoctorRow {
@@ -41,11 +42,14 @@ export interface PayloadTriple {
41
42
  }
42
43
 
43
44
  // One row's doctor section: the pure triple probes (run early — their
44
- // results print in the shell's opening checks) and the deferred
45
- // native-freshness checks (run late, after the stale-copy scan).
45
+ // results print in the shell's opening checks), the deferred
46
+ // native-freshness checks (run late, after the stale-copy scan), and the
47
+ // integrity receipt comparison (the integrity unit's layer 3 — run beside
48
+ // the triple, where the payload health prints).
46
49
  export interface PayloadDoctorSection {
47
50
  triple: PayloadTriple;
48
51
  nativeFreshness(ctx: DoctorReporter): void;
52
+ integrity(ctx: DoctorReporter): void;
49
53
  }
50
54
 
51
55
  // What a PAYLOAD_TARGETS row binds as its doctor section.
@@ -63,6 +67,12 @@ export function skillsTreeMatches(dir: string, expectedSkills: readonly string[]
63
67
 
64
68
  // The generic per-row section: the triple over the row's plugin dir plus the
65
69
  // receipt-gated native-freshness checks over the row's native dirs.
70
+ // The generic per-row section: the triple over the row's plugin dir plus
71
+ // the receipt-gated native-freshness checks over the row's native dirs,
72
+ // plus the deployed-classifier integrity comparison (layer 3). Rows
73
+ // without a deployed safety payload stay silent; a payload without a
74
+ // receipt (a pre-integrity install) WARNs — backward compatibility, never
75
+ // a false red; drift FAILs with the reinstall remediation.
66
76
  export function payloadDoctorSection(row: PayloadDoctorRow, shared: DoctorSharedState): PayloadDoctorSection {
67
77
  const dir = row.dir();
68
78
  return {
@@ -73,5 +83,33 @@ export function payloadDoctorSection(row: PayloadDoctorRow, shared: DoctorShared
73
83
  skillsTree: skillsTreeMatches(dir, shared.expectedSkills),
74
84
  },
75
85
  nativeFreshness: (ctx) => nativeFreshnessChecks(ctx, row, shared.corePack),
86
+ integrity: (ctx) => payloadIntegrityCheck(ctx, row.label, dir),
76
87
  };
77
88
  }
89
+
90
+ export function payloadIntegrityCheck(ctx: DoctorReporter, label: string, dir: string): void {
91
+ const status = verifyIntegrity(dir);
92
+ if (status.status === 'no-payload') return;
93
+ if (status.status === 'match') {
94
+ ctx.pass(`Safety policy integrity (${label})`);
95
+ return;
96
+ }
97
+ if (status.status === 'no-receipt') {
98
+ ctx.warn(
99
+ `Safety policy integrity (${label}) — integrity receipt missing (payload predates integrity tracking); re-run: npx huaweicloud-devkit install`,
100
+ );
101
+ return;
102
+ }
103
+ const all = [...status.drifted, ...status.missing, ...status.unrecorded];
104
+ const parts = [
105
+ status.drifted.length > 0 ? `${status.drifted.length} changed` : '',
106
+ status.missing.length > 0 ? `${status.missing.length} missing` : '',
107
+ status.unrecorded.length > 0 ? `${status.unrecorded.length} unrecorded` : '',
108
+ ].filter(Boolean);
109
+ const names = `${all.slice(0, 3).join(', ')}${all.length > 3 ? ', …' : ''}`;
110
+ ctx.check(
111
+ `Safety policy integrity (${label})`,
112
+ false,
113
+ `${parts.join(', ')} classifier file(s) (${names}) — Run: npx huaweicloud-devkit install`,
114
+ );
115
+ }
@@ -13,6 +13,17 @@
13
13
  // Mitigations: the tree is regenerated by every install/update
14
14
  // (copyServerPayload), and the PreToolUse hook still denies hcloud writes.
15
15
  //
16
+ // The payload root is the seam's EDIT-ONLY class (the interrogate round's
17
+ // classifier-rewrite finding): the deployed dist/safety-policy.js is what
18
+ // the in-process evaluate gate imports at runtime, so an edit-tool rewrite
19
+ // disarms the gate mid-session. The edit deny closes that tool vector; the
20
+ // external_directory allow is deliberately NOT extended to the payload —
21
+ // an allowed external directory inherits workspace defaults where bash is
22
+ // allowed, and the payload must not become a no-prompt bash write target.
23
+ // The bash-face residual is disclosed in the approvals reference and the
24
+ // changelog (the architectural fix direction is install-time integrity
25
+ // verification, out of scope here).
26
+ //
16
27
  // Ownership rules (no receipt, by judgment recorded in the changelog): two
17
28
  // keys over devkit-only globs — any rule on these globs is devkit-domain by
18
29
  // construction, so add-only-if-absent (a pre-existing rule with ANY value is
@@ -55,6 +66,14 @@ export function skillTreePermissionGlobs(
55
66
  return globs;
56
67
  }
57
68
 
69
+ // The edit-only class: the payload root (dist/, safety/, node_modules —
70
+ // everything the deployed gate imports or executes). Edit/write/patch tools
71
+ // deny there, but the external_directory allow is deliberately NOT
72
+ // extended: the payload must not become a no-prompt bash write target.
73
+ export function payloadEditDenyGlobs(pluginDir: string): string[] {
74
+ return [`${pluginDir.replace(/\\/g, '/')}/**`];
75
+ }
76
+
58
77
  export interface SeamApplyResult {
59
78
  changed: boolean;
60
79
  // Section names whose shape was not an object ('permission' for the
@@ -63,14 +82,39 @@ export interface SeamApplyResult {
63
82
  skipped: string[];
64
83
  }
65
84
 
85
+ // The per-section resolver shared by apply and remove: the section record
86
+ // (fresh when absent, so the caller's writes land and are assigned back),
87
+ // or null when the user owns a scalar shape there — one ownership check in
88
+ // one place for both directions of the seam.
89
+ function sectionFor(permission: Record<string, unknown>, key: string): Record<string, unknown> | null {
90
+ if (permission[key] !== undefined && !isRecord(permission[key])) return null;
91
+ return asRecord(permission[key]);
92
+ }
93
+
94
+ // The two-class section table shared by apply and remove: the external
95
+ // allow covers the skills globs only, the edit deny covers them plus the
96
+ // edit-only payload class.
97
+ function seamSections(
98
+ globs: readonly string[],
99
+ editOnlyGlobs: readonly string[],
100
+ ): Array<readonly [key: string, value: 'allow' | 'deny', list: readonly string[]]> {
101
+ return [
102
+ ['external_directory', 'allow', globs],
103
+ ['edit', 'deny', [...globs, ...editOnlyGlobs]],
104
+ ];
105
+ }
106
+
66
107
  // Mutates config in place. Add-only-if-absent per section: a glob already
67
108
  // present with ANY value keeps the user's rule; only missing globs get the
68
109
  // devkit value. Appended keys win under OpenCode's last-matching-rule-wins
69
110
  // evaluation — deliberate, so the devkit's specific allow beats an earlier
70
- // broader user pattern (e.g. "~/.config/opencode/**": "ask").
111
+ // broader user pattern (e.g. "~/.config/opencode/**": "ask"). The edit-only
112
+ // class writes the edit section alone; the external allow deliberately
113
+ // never covers it (see the module header).
71
114
  export function applySkillTreePermissionSeam(
72
115
  config: Record<string, unknown>,
73
116
  globs: readonly string[],
117
+ editOnlyGlobs: readonly string[] = [],
74
118
  ): SeamApplyResult {
75
119
  if (config.permission !== undefined && !isRecord(config.permission)) {
76
120
  // The whole-config string form ("permission": "allow") is the user's
@@ -81,17 +125,13 @@ export function applySkillTreePermissionSeam(
81
125
  const permission = asRecord(config.permission);
82
126
  const skipped: string[] = [];
83
127
  let changed = false;
84
- const sections: Array<readonly [key: string, value: 'allow' | 'deny']> = [
85
- ['external_directory', 'allow'],
86
- ['edit', 'deny'],
87
- ];
88
- for (const [key, value] of sections) {
89
- if (permission[key] !== undefined && !isRecord(permission[key])) {
128
+ for (const [key, value, list] of seamSections(globs, editOnlyGlobs)) {
129
+ const section = sectionFor(permission, key);
130
+ if (section === null) {
90
131
  skipped.push(key);
91
132
  continue;
92
133
  }
93
- const section = asRecord(permission[key]);
94
- const missing = globs.filter((glob) => !Object.hasOwn(section, glob));
134
+ const missing = list.filter((glob) => !Object.hasOwn(section, glob));
95
135
  if (missing.length === 0) continue;
96
136
  for (const glob of missing) section[glob] = value;
97
137
  permission[key] = section;
@@ -104,20 +144,21 @@ export function applySkillTreePermissionSeam(
104
144
  // Mutates config in place. Value-exact deletion only — a user-modified value
105
145
  // on a devkit glob survives. Sections emptied by OUR deletions are pruned
106
146
  // (a pre-existing empty section is left untouched), and the permission
107
- // object itself is pruned only when the seam emptied it.
108
- export function removeSkillTreePermissionSeam(config: Record<string, unknown>, globs: readonly string[]): boolean {
147
+ // object itself is pruned only when the seam emptied it. The edit-only
148
+ // class is removed from the edit section under the same value-exact rule.
149
+ export function removeSkillTreePermissionSeam(
150
+ config: Record<string, unknown>,
151
+ globs: readonly string[],
152
+ editOnlyGlobs: readonly string[] = [],
153
+ ): boolean {
109
154
  if (!isRecord(config.permission)) return false;
110
155
  const permission = asRecord(config.permission);
111
156
  let changed = false;
112
- const sections: Array<readonly [key: string, value: 'allow' | 'deny']> = [
113
- ['external_directory', 'allow'],
114
- ['edit', 'deny'],
115
- ];
116
- for (const [key, value] of sections) {
117
- if (!isRecord(permission[key])) continue;
118
- const section = asRecord(permission[key]);
157
+ for (const [key, value, list] of seamSections(globs, editOnlyGlobs)) {
158
+ const section = sectionFor(permission, key);
159
+ if (section === null) continue;
119
160
  let removedHere = false;
120
- for (const glob of globs) {
161
+ for (const glob of list) {
121
162
  if (section[glob] === value) {
122
163
  delete section[glob];
123
164
  removedHere = true;
@@ -158,6 +158,12 @@ async function handleAuthSwitch(args: ToolArgs = {}, opts: CallToolOptions = {})
158
158
  return persisted;
159
159
  }
160
160
 
161
+ // F-APV-1: the confirm-token rejection spells its way out (exported for the
162
+ // test that pins the envelope). Confirm tokens share the approval tokens'
163
+ // process-scoped lifetime: a restart drops every pending confirm.
164
+ export const AUTH_CONFIRM_TOKEN_NOT_FOUND_NEXT_STEP =
165
+ 'This confirmation token was never minted in this process — mistyped, or dropped by a server restart (confirm tokens are process-scoped and never persisted). Re-run the huaweicloud_auth_switch action that returned needs_confirmation to mint a fresh token, then call huaweicloud_auth_confirm with it.';
166
+
161
167
  async function handleAuthConfirm(args: ToolArgs = {}, _opts: CallToolOptions = {}) {
162
168
  // D4-24 precise JSON contract (#745): a missing or already-consumed confirm
163
169
  // token returns a structured result instead of throwing a generic Error
@@ -173,7 +179,7 @@ async function handleAuthConfirm(args: ToolArgs = {}, _opts: CallToolOptions = {
173
179
  if (token && consumedConfirms.has(token)) {
174
180
  return { status: 'ok', outcome: 'already_processed' };
175
181
  }
176
- return { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND' };
182
+ return { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND', nextStep: AUTH_CONFIRM_TOKEN_NOT_FOUND_NEXT_STEP };
177
183
  }
178
184
  if (args.decision === 's1') {
179
185
  pendingConfirms.delete(token);
@@ -3,6 +3,7 @@ import { join } from 'node:path';
3
3
 
4
4
  import { copyDir, copyFileVerified, pruneStale } from './payload-files.ts';
5
5
  import { PLUGIN_ROOT } from './payload-utils.ts';
6
+ import { writeIntegrityReceipt } from './safety-integrity.ts';
6
7
 
7
8
  // The server-payload placement (the install-payload.ts internals split):
8
9
  // the one shared seam every per-agent install/update call site ships the
@@ -74,6 +75,13 @@ export function copyServerPayload(pluginDest: string, opts: { skipDist?: boolean
74
75
  }
75
76
  copyDir(join(PLUGIN_ROOT, 'safety'), join(pluginDest, 'safety'));
76
77
  console.log(` Safety Policy -> ${join(pluginDest, 'safety')}`);
78
+ // The integrity receipt (the integrity unit's layer 3): a hash manifest
79
+ // of the classifier files that just landed, written at the one shared
80
+ // placement seam so every install/update path records it and doctor can
81
+ // detect drift later. Covers whatever shipped — a skipDist payload
82
+ // records its safety/ files only.
83
+ writeIntegrityReceipt(pluginDest);
84
+ console.log(` Integrity receipt -> ${join(pluginDest, '.safety-integrity.json')}`);
77
85
  const skillsSrc = join(PLUGIN_ROOT, 'skills');
78
86
  // A missing source tree must abort, not silently skip: copyDir's
79
87
  // existsSync guard would no-op the copy while this function still prints
@@ -4,6 +4,7 @@ import { classifyHcloudArgs } from './classify-hcloud.ts';
4
4
  import { credentialFileCandidates } from './credential-path.ts';
5
5
  import { DEFAULT_POLICY } from './default-policy.ts';
6
6
  import { matchesAny, type ClassifyOptions } from './policy.ts';
7
+ import { protectedPayloadWriteDenied } from './protected-payload.ts';
7
8
  import { applyRawCommandRiskRules } from './risk-merge.ts';
8
9
  import { unwrapSecretExecWrapper } from './secret-exec.ts';
9
10
  import { unwrapSkillQualityCli } from './skill-quality-cli.ts';
@@ -828,6 +829,15 @@ export function classifyTextCommand(command: unknown, options: ClassifyOptions =
828
829
  };
829
830
  }
830
831
 
832
+ // The payload path-write gate (the integrity unit's layer 1): the same
833
+ // candidate doctrine as the credential gate, but WRITE-shaped — a
834
+ // redirection/tee/copy-family/dd/sed -i/patch command targeting a
835
+ // protectedPayloadPathMarkers path denies (the bash-face disarm vector
836
+ // the edit seam closed for edit tools; protected-payload.ts owns the
837
+ // shape spec, mirrored by the py twin after its CONFIG_FILE_RE gate).
838
+ const payloadWrite = protectedPayloadWriteDenied(text, policy);
839
+ if (payloadWrite !== null) return payloadWrite;
840
+
831
841
  // The vault CLI's own reveal surface: `secret get` prints a stored secret
832
842
  // to stdout, which is the agent context when run through the Bash tool.
833
843
  // `secret exec` (values reach only the child env) stays allowed. Matched
@@ -7,6 +7,7 @@ import { stripShellQuotes } from './shell-text.ts';
7
7
  export interface Policy {
8
8
  secretKeyNamePatterns: string[];
9
9
  credentialFilePatterns: string[];
10
+ protectedPayloadPathMarkers: string[];
10
11
  blockedConfigureSubcommands: string[];
11
12
  blockedSecretOperations: string[];
12
13
  blockedSecretCliPatterns: string[];
@@ -59,9 +60,21 @@ export function loadPolicy(path: string): Policy {
59
60
  if (raw.writeOperationPrefixes !== undefined && writeOperationPrefixes.length === 0) {
60
61
  throw new TypeError('safety policy field "writeOperationPrefixes" must not be empty');
61
62
  }
63
+ const protectedPayloadPathMarkers = toStringArray(raw.protectedPayloadPathMarkers, 'protectedPayloadPathMarkers');
64
+ // Same emptied-list doctrine as writeOperationPrefixes: a present-but-empty
65
+ // marker list silently disarms the payload path-write gate, so it fails
66
+ // LOUD at load. The py twin has no load-time throw (its load_policy catches
67
+ // everything) and normalizes the degraded shape to an unset gate — the
68
+ // recorded py fail-open posture for a hand-corrupted policy file, the same
69
+ // divergence class the write vocabulary carries (the .mjs face is the
70
+ // fail-closed one).
71
+ if (raw.protectedPayloadPathMarkers !== undefined && protectedPayloadPathMarkers.length === 0) {
72
+ throw new TypeError('safety policy field "protectedPayloadPathMarkers" must not be empty');
73
+ }
62
74
  return {
63
75
  secretKeyNamePatterns: toStringArray(raw.secretKeyNamePatterns, 'secretKeyNamePatterns'),
64
76
  credentialFilePatterns: toStringArray(raw.credentialFilePatterns, 'credentialFilePatterns'),
77
+ protectedPayloadPathMarkers,
65
78
  blockedConfigureSubcommands: toStringArray(raw.blockedConfigureSubcommands, 'blockedConfigureSubcommands'),
66
79
  blockedSecretOperations: toStringArray(raw.blockedSecretOperations, 'blockedSecretOperations'),
67
80
  blockedSecretCliPatterns: toStringArray(raw.blockedSecretCliPatterns, 'blockedSecretCliPatterns'),
@@ -0,0 +1,97 @@
1
+ import type { RiskDecision } from '../risk-rule-engine.ts';
2
+ import { credentialFileCandidates } from './credential-path.ts';
3
+ import type { Policy } from './default-policy.ts';
4
+
5
+ // The payload path-write gate (the integrity unit's layer 1): a
6
+ // write-shaped shell command that targets the DEPLOYED devkit payload —
7
+ // the classifier files the in-process gates import — denies. The residual
8
+ // it closes: PR #22's seam killed the edit-tool vector on the deployed
9
+ // classifier, but the bash face could still `echo '<permissive>' >
10
+ // …/dist/safety-policy.js` and the adapter's lazy, retryable import loaded
11
+ // the agent's file, disarming every in-process gate mid-session (the TLA
12
+ // counterexample path). READ-shaped references stay allowed: skills reads,
13
+ // skill-tracker, doctor, and plain `cat`/`ls`/`grep` over the payload tree
14
+ // are legitimate agent surface.
15
+ //
16
+ // Write-shape spec (mirrored by the py twin's evaluate gate — keep the two
17
+ // byte-identical in verdicts):
18
+ // candidates: raw text, quote-stripped shadow, path-normalized both (the
19
+ // credentialFileCandidates doctrine — a quote pair inside the path or a
20
+ // redundant `//`/`./` segment must not hide the marker);
21
+ // chunks: each candidate splits on [;&|\n\r] — a crude split, deliberately:
22
+ // it can only over-SPLIT (a separator inside quotes is part of a FILE
23
+ // NAME, and a real payload path never carries one), never join, so a
24
+ // detection can only be lost on non-payload targets;
25
+ // shapes, per chunk (MARKER = the policy alternation):
26
+ // 1. redirect />>?[^;&|]*MARKER/ — target-side marker
27
+ // 2. tee anchor + tee … MARKER — tee's operands are targets
28
+ // 3. cp|mv|rsync|install anchor + … final word carries MARKER (dest)
29
+ // 4. dd anchor + … of=… MARKER — of= is the output
30
+ // 5. sed anchor + … -i … MARKER — in-place edit target
31
+ // 6. patch anchor + … MARKER — operand is the target
32
+ // anchor: chunk start, optional env assignments, then optional
33
+ // sudo/env/nice/nohup/command/xargs heads — command position for the
34
+ // write verbs, so `grep tee <marker-file>` (a read) never trips.
35
+ // Whitespace classes are [ \t] (bash IFS without newline — chunks carry no
36
+ // newlines), keeping JS/py classes identical.
37
+ //
38
+ // Honest ceiling (documented, not closed): quote/variable indirection
39
+ // building the marker path, `cp -t`-style flag targets, timeout-wrapped
40
+ // write verbs, and verbs outside the shape table (truncate/ln/…) are
41
+ // residuals of a text gate; rm/rename of payload files break the gate
42
+ // fail-closed at import time rather than disarm it. Against arbitrary
43
+ // user-permission bash NO purely local mechanism fully closes this — the
44
+ // layer-2 load-time canary and the layer-3 doctor drift check raise the
45
+ // escape cost to forging multiple artifacts.
46
+
47
+ // The shape fragments are shared verbatim with the py twin. Every \s in
48
+ // them is [ \t]; MARKER substitutes the policy alternation.
49
+ function shapeRegexes(markers: string[]): RegExp[] {
50
+ if (markers.length === 0) return [];
51
+ const markerAlt = `(?:${markers.join('|')})`;
52
+ const anchor = String.raw`^[ \t]*(?:[A-Za-z_][A-Za-z0-9_]*=\S*[ \t]+)*(?:(?:sudo|env|nice|nohup|command|xargs)[ \t]+)*`;
53
+ return [
54
+ // 1. Redirection: the marker sits in the redirect's target region.
55
+ // Direction is inherent — `cat <marker> > /tmp/out` keeps its marker
56
+ // BEFORE the operator and never matches.
57
+ new RegExp(String.raw`>>?[^;&|]*` + markerAlt, 'i'),
58
+ // 2. tee: every operand is a write target.
59
+ new RegExp(anchor + String.raw`tee\b[^;&|]*` + markerAlt, 'i'),
60
+ // 3. The copy family: the destination is the LAST operand, so the
61
+ // marker must ride the final word — `cp <marker> /tmp/` (a copy-out)
62
+ // stays allowed.
63
+ new RegExp(anchor + String.raw`(?:cp|mv|rsync|install)\b[^;&|]*[ \t]\S*` + markerAlt + String.raw`\S*[ \t]*$`, 'i'),
64
+ // 4. dd: the of= operand is the output.
65
+ new RegExp(anchor + String.raw`dd\b[^;&|]*\bof[ \t]*=[ \t]*[^;&|]*` + markerAlt, 'i'),
66
+ // 5. sed: a whitespace-preceded -i flag (in-place) anywhere before the
67
+ // marker; a read-only sed over the payload stays allowed.
68
+ new RegExp(anchor + String.raw`sed\b[^;&|]*[ \t]-i\b[^;&|]*` + markerAlt, 'i'),
69
+ // 6. patch: the operand is the file being patched.
70
+ new RegExp(anchor + String.raw`patch\b[^;&|]*` + markerAlt, 'i'),
71
+ ];
72
+ }
73
+
74
+ export function protectedPayloadWriteDenied(text: string, policy: Policy): RiskDecision | null {
75
+ if (policy.protectedPayloadPathMarkers.length === 0) return null;
76
+ const shapes = shapeRegexes(policy.protectedPayloadPathMarkers);
77
+ // The candidates a path-bearing gate tests (the credential gate's set):
78
+ // quoting and path redundancy must not hide the marker.
79
+ for (const candidate of credentialFileCandidates(text)) {
80
+ for (const chunk of candidate.split(/[;&|\n\r]/)) {
81
+ for (const shape of shapes) {
82
+ if (shape.test(chunk)) {
83
+ return {
84
+ decision: 'deny',
85
+ // risk 'invalid': exempt from NO roster exemption class (the
86
+ // .mjs/py hooks skip write/execution/destructive for exempt
87
+ // shapes — a payload-write deny must never be skippable).
88
+ risk: 'invalid',
89
+ reason:
90
+ "Writing to the deployed Huawei Cloud DevKit plugin payload is blocked: this command targets the installed safety policy files, and modifying them would disarm the gates that classify agent commands. Reinstall or update via npx huaweicloud-devkit install from your own terminal; see the huaweicloud-safety skill's approvals reference for the integrity model.",
91
+ };
92
+ }
93
+ }
94
+ }
95
+ }
96
+ return null;
97
+ }