Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
feat(quality): allow operator-supplied red-flag rules
Harbor404684c604e8306
diff --git a/src/main/quality/README.md b/src/main/quality/README.mdindex 759e6b09..98173b11 100644--- a/src/main/quality/README.md+++ b/src/main/quality/README.md@@ -41,6 +41,19 @@ quality/3. Run `npm test` (NOT `npx vitest` — the wrapper runs Vitest through Electron's embedded Node so native addons use the app ABI).4. Bump `VALIDATOR_VERSION` in `types.ts` if the change is observable by callers (existing reports written under the old version stay valid).+## Operator policy rules++Teams can add their own red flags without forking: write a JSON rule file,+parse it with `parseOperatorPolicy` (exported from `index.ts`; reading the+file is the caller's job — `quality/` stays stateless), then pass the parsed+rules as `operatorRules` to `validateSkillFile` / `validateSkillDir` /+`validateAgentSpec` / `validateAgentDir`.++The built-in rules stay the security floor: operator rules are additive only+— they never suppress, downgrade or rewrite a built-in finding, and a+colliding id is rejected. Their findings carry `source: 'operator-policy'`.+Still not a sandbox. Field reference lives in `rules/operator-policy.ts`.+## Levels| Level | Behavior |@@ -66,7 +79,8 @@ There is intentionally NO override for EXTREME. If a real use case triggers a re- Capability cross-check against the tool catalog — deferred to phase 1.- Similarity check — deferred to phase 2 (embedding-based).- Outbound HTTP detection — deferred to phase 2 (runtime network sandbox is the right layer).-- User-defined red flags — not exposed; the rule list is build-time only.+- Rule *authoring* for the built-in floor is still build-time; teams that need+ their own extra rules use the additive operator layer below.## Testsdiff --git a/src/main/quality/index.ts b/src/main/quality/index.tsindex 489d3d4e..826cf744 100644--- a/src/main/quality/index.ts+++ b/src/main/quality/index.ts@@ -22,11 +22,13 @@import * as fs from 'node:fs';import * as path from 'node:path';-import { Violation, ValidationReport, ScanKind, VALIDATOR_VERSION } from './types';+import { Violation, ValidationReport, ScanKind, RuleDef, VALIDATOR_VERSION } from './types';import {scanRedFlags,+ scanRuleSet,extractExecutableBlocks,} from './rules/red-flags';+import type { RuleScanArgs } from './rules/red-flags';import {validateSkillFrontmatter,validateSkillMeta,@@ -42,6 +44,8 @@ import {// Re-export the types so callers only need one import path.export type { Violation, ValidationReport, Level } from './types';export { VALIDATOR_VERSION } from './types';+export { parseOperatorPolicy } from './rules/operator-policy';+export type { OperatorPolicyParseResult } from './rules/operator-policy';export type SkillValidationSource =| 'custom'@@ -55,6 +59,10 @@ export interface SkillValidationOptions {* required. System freshness belongs to its manifest; private-Skill* freshness and category belong to the parent Agent. */source?: SkillValidationSource;+ /** Extra operator-supplied rules (see `parseOperatorPolicy`). Purely+ * additive: they add `source: 'operator-policy'` findings and can never+ * suppress or downgrade a built-in one. */+ operatorRules?: ReadonlyArray<RuleDef>;}// ── File-level skill validation ─────────────────────────────────────────@@ -66,20 +74,23 @@ export interface SkillValidationOptions {export function validateSkillFile(args: {relpath: string;content: string;+ operatorRules?: ReadonlyArray<RuleDef>;}): ValidationReport {const violations: Violation[] = [];const kind = detectSkillFileKind(args.relpath);if (kind === 'skill_md') {- violations.push(..._scanSkillMd(args.content, args.relpath));+ violations.push(..._scanSkillMd(args.content, args.relpath, {}, true, false, args.operatorRules));} else if (kind === 'skill_meta') {violations.push(..._scanSkillMeta(args.content));} else if (kind === 'script') {- violations.push(...scanRedFlags({+ const scanArgs: RuleScanArgs = {content: args.content,kind: 'script',field: args.relpath,- }));+ };+ violations.push(...scanRedFlags(scanArgs));+ violations.push(..._policyScan(args.operatorRules, scanArgs));}// kind === 'other' (README / assets) → no scan@@ -122,6 +133,7 @@ export function validateSkillDir(meta,options.enforceSkillRunner !== false,options.source === 'system',+ options.operatorRules,));if (options.source !== 'system' && options.source !== 'agent-private') {violations.push(...validateSkillMeta(meta));@@ -142,7 +154,9 @@ export function validateSkillDir(if (kind !== 'script') continue;try {const content = fs.readFileSync(path.join(skillDir, rel), 'utf8');- violations.push(...scanRedFlags({ content, kind: 'script', field: rel }));+ const scanArgs: RuleScanArgs = { content, kind: 'script', field: rel };+ violations.push(...scanRedFlags(scanArgs));+ violations.push(..._policyScan(options.operatorRules, scanArgs));} catch {// unreadable file (binary / permission) — skip; no violation surfaced}@@ -160,6 +174,7 @@ export function validateSkillDir(export function validateAgentSpec(args: {agentJson: unknown;enforceSkillRunner?: boolean;+ operatorRules?: ReadonlyArray<RuleDef>;}): ValidationReport {const violations: Violation[] = [];if (!args.agentJson || typeof args.agentJson !== 'object') {@@ -180,11 +195,13 @@ export function validateAgentSpec(args: {// application uniform — we don't need per-field traversal at this scope.try {const serialized = JSON.stringify(obj);- violations.push(...scanRedFlags({+ const scanArgs: RuleScanArgs = {content: serialized,kind: 'agent_json',field: 'agent.json',- }));+ };+ violations.push(...scanRedFlags(scanArgs));+ violations.push(..._policyScan(args.operatorRules, scanArgs));} catch {// unserializable (cyclic) → not worth surfacing here, the shape check// above would have already failed on the broken structure@@ -198,7 +215,7 @@ export function validateAgentSpec(args: {*/export function validateAgentDir(agentDir: string,- options: { enforceSkillRunner?: boolean } = {},+ options: { enforceSkillRunner?: boolean; operatorRules?: ReadonlyArray<RuleDef> } = {},): ValidationReport {const file = path.join(agentDir, 'agent.json');if (!fs.existsSync(file)) {@@ -222,11 +239,20 @@ export function validateAgentDir(return validateAgentSpec({agentJson: parsed,enforceSkillRunner: options.enforceSkillRunner,+ operatorRules: options.operatorRules,});}// ── Internals ───────────────────────────────────────────────────────────+/** Additive scan; empty input yields [] so opted-out callers stay identical. */+function _policyScan(+ rules: ReadonlyArray<RuleDef> | undefined,+ args: RuleScanArgs,+): Violation[] {+ return scanRuleSet(rules ?? [], args, 'operator-policy');+}+function detectSkillFileKind(relpath: string): ScanKind {const norm = relpath.replace(/\\/g, '/');if (norm.toUpperCase() === 'SKILL.MD') return 'skill_md';@@ -245,6 +271,7 @@ function _scanSkillMd(skillMeta: Record<string, unknown> = {},enforceSkillRunner = true,allowFrontmatterExtensions = false,+ operatorRules?: ReadonlyArray<RuleDef>,): Violation[] {const violations: Violation[] = [];@@ -268,11 +295,13 @@ function _scanSkillMd(// Embedded executable code blocks: scan each for red flags.for (const block of extractExecutableBlocks(body)) {- violations.push(...scanRedFlags({+ const scanArgs: RuleScanArgs = {content: block.content,kind: 'script', // executable block → treat as scriptfield: `${field}:${block.startLine} (\`\`\`${block.lang})`,- }));+ };+ violations.push(...scanRedFlags(scanArgs));+ violations.push(..._policyScan(operatorRules, scanArgs));}return violations;diff --git a/src/main/quality/rules/operator-policy.ts b/src/main/quality/rules/operator-policy.tsnew file mode 100644index 00000000..863ace79--- /dev/null+++ b/src/main/quality/rules/operator-policy.ts@@ -0,0 +1,100 @@+/**+ * Operator policy rules — additive red flags supplied by an operator at+ * runtime. RED_FLAGS stays the security floor: rules here can only ADD+ * findings, never suppress or downgrade a built-in one, and a colliding id is+ * rejected. Findings carry `source: 'operator-policy'`. Pure: no filesystem.+ */++import { Level, RuleDef, ScanKind } from '../types';+import { RED_FLAGS } from './red-flags';+const KINDS: ReadonlyArray<ScanKind> = ['skill_md', 'skill_meta', 'script', 'agent_json'];+const DEFAULT_APPLIES_TO: ScanKind[] = ['skill_md', 'script', 'agent_json'];+const MAX_RULES = 50;+const MAX_PATTERN = 500;+const RULE_ID = /^[a-z0-9][a-z0-9_.-]{0,63}$/;+const ALLOWED_FLAGS = /^[imsu]*$/;++export interface OperatorPolicyParseResult {+ rules: RuleDef[];+ /** Reasons individual rules were skipped (never thrown). */+ errors: string[];+}++/** Parse an operator rule file (`{ "rules": [ ... ] }`). Invalid rules are+ * skipped and reported in `errors`; the rest still load. */+export function parseOperatorPolicy(content: string): OperatorPolicyParseResult {+ let parsed: unknown;+ try {+ parsed = JSON.parse(content);+ } catch (err) {+ return { rules: [], errors: [`operator policy is not valid JSON: ${(err as Error).message}`] };+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ return { rules: [], errors: ['operator policy must be a JSON object like { "rules": [...] }'] };+ }+ const raw = (parsed as { rules?: unknown }).rules;+ if (!Array.isArray(raw)) {+ return { rules: [], errors: ['operator policy must contain a "rules" array'] };+ }++ const errors: string[] = [];+ if (raw.length > MAX_RULES) errors.push(`operator policy has ${raw.length} rules; only the first ${MAX_RULES} load`);++ const builtinIds = new Set(RED_FLAGS.map((r) => r.id));+ const seen = new Set<string>();+ const rules: RuleDef[] = [];++ for (const [i, entry] of raw.slice(0, MAX_RULES).entries()) {+ const where = `rules[${i}]`;+ const fail = (msg: string) => { errors.push(`${where}: ${msg}`); };+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) { fail('must be an object'); continue; }+ const r = entry as Record<string, unknown>;++ const id = typeof r.id === 'string' ? r.id.trim() : '';+ if (!RULE_ID.test(id)) { fail(`"id" must match ${RULE_ID}`); continue; }+ if (builtinIds.has(id)) { fail(`id "${id}" collides with a built-in rule; operator rules may not shadow the security floor`); continue; }+ if (seen.has(id)) { fail(`duplicate id "${id}"`); continue; }++ const level = r.level;+ if (level !== 'EXTREME' && level !== 'MEDIUM' && level !== 'LOW') { fail('"level" must be EXTREME, MEDIUM, or LOW'); continue; }++ const src = typeof r.pattern === 'string' ? r.pattern : '';+ if (!src || src.length > MAX_PATTERN) { fail(`"pattern" must be a non-empty string of at most ${MAX_PATTERN} chars`); continue; }++ // `g` / `y` are stateful (`lastIndex`) and one rule object is reused across files.+ const flags = typeof r.flags === 'string' ? r.flags : '';+ if (!ALLOWED_FLAGS.test(flags)) { fail('"flags" may only contain i, m, s, u'); continue; }++ let pattern: RegExp;+ try { pattern = new RegExp(src, flags); }+ catch (err) { fail(`invalid regex: ${(err as Error).message}`); continue; }++ const message = typeof r.message === 'string' ? r.message.trim().slice(0, 300) : '';++ const appliesTo = _appliesTo(r.appliesTo, where, errors);+ if (!appliesTo) continue;++ seen.add(id);+ rules.push({+ id,+ level: level as Level,+ appliesTo,+ pattern,+ suggested_fix: message+ || `Operator policy "${id}" matched. Rewrite the spec so it no longer matches, or ask the operator to revise this policy.`,+ });+ }++ return { rules, errors };+}++function _appliesTo(raw: unknown, where: string, errors: string[]): ScanKind[] | null {+ if (raw === undefined) return [...DEFAULT_APPLIES_TO];+ const list = Array.isArray(raw) ? raw : [];+ const bad = !list.length || list.some((k) => typeof k !== 'string' || !KINDS.includes(k as ScanKind));+ if (bad) {+ errors.push(`${where}: "appliesTo" must be a non-empty array of ${KINDS.join(' | ')}`);+ return null;+ }+ return list as ScanKind[];+}diff --git a/src/main/quality/rules/red-flags.ts b/src/main/quality/rules/red-flags.tsindex 8293eeaf..ff4f5553 100644--- a/src/main/quality/rules/red-flags.ts+++ b/src/main/quality/rules/red-flags.ts@@ -17,7 +17,7 @@* ("this skill handles ssh config" ≠ "reads ssh private keys").*/-import { RuleDef, ScanKind, Violation } from '../types';+import { RuleDef, ScanKind, Violation, ViolationSource } from '../types';// ── Rule list ────────────────────────────────────────────────────────────@@ -108,18 +108,27 @@ export const RED_FLAGS: ReadonlyArray<RuleDef> = [// ── Application ──────────────────────────────────────────────────────────-/**- * Scan content + return violations from the matching rules.- * `kind === 'other'` returns []; no scanning of prose / docs / assets.- */-export function scanRedFlags(args: {+export interface RuleScanArgs {content: string;kind: ScanKind;field: string; // path-like locator for the report-}): Violation[] {+}++/**+ * Scan content against an arbitrary rule list.+ * `kind === 'other'` returns []; no scanning of prose / docs / assets.+ *+ * `source` tags the produced findings. Built-in callers omit it, so built-in+ * violations stay byte-identical to previous validator versions.+ */+export function scanRuleSet(+ rules: ReadonlyArray<RuleDef>,+ args: RuleScanArgs,+ source?: ViolationSource,+): Violation[] {if (args.kind === 'other') return [];const out: Violation[] = [];- for (const rule of RED_FLAGS) {+ for (const rule of rules) {if (!rule.appliesTo.includes(args.kind)) continue;const match = rule.pattern.exec(args.content);if (!match) continue;@@ -131,6 +140,7 @@ export function scanRedFlags(args: {field: lineNo > 0 ? `${args.field}:${lineNo}` : args.field,snippet,suggested_fix: rule.suggested_fix,+ ...(source ? { source } : {}),});// Reset stateful regex (`/g`) — we don't use /g but be safe across future// changes by zeroing lastIndex.@@ -139,6 +149,11 @@ export function scanRedFlags(args: {return out;}+/** Scan content against the built-in red-flag floor. */+export function scanRedFlags(args: RuleScanArgs): Violation[] {+ return scanRuleSet(RED_FLAGS, args);+}+/*** Extract fenced code blocks of executable languages from a SKILL.md body* and yield each block paired with its kind for further scanning.diff --git a/src/main/quality/types.ts b/src/main/quality/types.tsindex 25d363a4..9a1973b6 100644--- a/src/main/quality/types.ts+++ b/src/main/quality/types.ts@@ -6,6 +6,10 @@export type Level = 'EXTREME' | 'MEDIUM' | 'LOW';+/** Origin of a finding. Absent = the built-in rule set (the security floor).+ * 'operator-policy' = added by an operator-supplied rule file at runtime. */+export type ViolationSource = 'operator-policy';+export interface Violation {level: Level;/** Stable rule id, e.g. "no_credential_path_read" — used by the LLM retry@@ -20,6 +24,9 @@ export interface Violation {snippet: string;/** One-line repair guidance — written for the LLM author + human reader. */suggested_fix: string;+ /** Set only for findings produced by operator-supplied policy rules. Built-in+ * findings leave this absent. */+ source?: ViolationSource;}export interface ValidationReport {diff --git a/test/main/quality/operator-policy.test.ts b/test/main/quality/operator-policy.test.tsnew file mode 100644index 00000000..86b2c8eb--- /dev/null+++ b/test/main/quality/operator-policy.test.ts@@ -0,0 +1,97 @@+import { describe, it, expect } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++import { validateSkillFile, validateSkillDir } from '../../../src/main/quality';+import { parseOperatorPolicy } from '../../../src/main/quality/rules/operator-policy';++type Rules = ReturnType<typeof parseOperatorPolicy>['rules'];++const POLICY = JSON.stringify({ rules: [+ { id: 'no_internal_bucket', level: 'EXTREME', pattern: 's3://acme-internal',+ message: 'Internal buckets are off limits for skills.' },+ { id: 'host_allowlist', level: 'MEDIUM', pattern: 'curl\\b[^\\n]*https?://(?!api\\.acme\\.example)',+ appliesTo: ['script'] },+] });++const md = (b: string) => ['---', 'name: internal-report', 'description: Build the weekly report', '---', b].join('\n');++function report(content: string, operatorRules?: Rules) {+ const r = validateSkillFile({ relpath: 'SKILL.md', content, operatorRules });+ return { ok: r.ok, violations: r.violations, validator_version: r.validator_version };+}+describe('quality › operator policy rules', () => {+ it('parses a valid rule file and applies the documented defaults', () => {+ const { rules, errors } = parseOperatorPolicy(POLICY);+ expect(rules.map((r) => r.id)).toEqual(['no_internal_bucket', 'host_allowlist']);+ expect(rules[0].appliesTo).toEqual(['skill_md', 'script', 'agent_json']);+ expect(rules[1].appliesTo).toEqual(['script']);+ });++ it('leaves the report byte-identical when no operator rules are configured', () => {+ const content = md('```bash\naws s3 cp s3://acme-internal/x .\n```\n');+ expect(report(content).violations).toEqual([]); // nothing on the built-in floor fires here+ for (const rules of [undefined, []]) expect(report(content, rules)).toEqual(report(content));+ });++ it('adds an operator finding tagged source=operator-policy', () => {+ const { rules } = parseOperatorPolicy(POLICY);+ const r = validateSkillFile({+ relpath: 'SKILL.md',+ content: md('```bash\naws s3 cp s3://acme-internal/x .\n```\n'),+ operatorRules: rules,+ });+ const hit = r.violations.find((v) => v.rule === 'no_internal_bucket');+ expect(hit).toMatchObject({ level: 'EXTREME', source: 'operator-policy' });+ expect(r.ok).toBe(false);+ });++ it('cannot suppress, downgrade, or rewrite a built-in finding', () => {+ const { rules } = parseOperatorPolicy(JSON.stringify({ rules: [+ { id: 'downgrade_attempt', level: 'LOW', pattern: 'security\\s+find-generic-password' }] }));+ const content = md('```bash\nsecurity find-generic-password -s x -w\n```\n');+ const before = report(content);+ const after = report(content, rules);+ expect(before.violations.find((v) => v.rule === 'no_credential_path_read')?.level).toBe('EXTREME');+ // Operator rules only ever add: every built-in finding survives unchanged.+ for (const v of before.violations) {+ expect(after.violations.find((x) => x.rule === v.rule && x.field === v.field)).toEqual(v);+ }+ expect(after.ok).toBe(false);+ });++ it('rejects malformed rules and ids that would shadow the floor', () => {+ expect(parseOperatorPolicy('{not json').errors[0]).toMatch(/not valid JSON/);+ expect(parseOperatorPolicy('{}').errors[0]).toMatch(/"rules" array/);+ const cases: Array<[unknown, RegExp]> = [+ [{ id: 'no_credential_path_read', level: 'LOW', pattern: 'x' }, /collides with a built-in rule/],+ ];+ for (const [rule, expected] of cases) {+ const parsed = parseOperatorPolicy(JSON.stringify({ rules: [rule] }));+ expect(parsed.rules).toEqual([]);+ expect(parsed.errors[0]).toMatch(expected);+ }+ });++ it('scans on-disk scripts, honours appliesTo, and never flips the floor verdict', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'quality-op-'));+ fs.writeFileSync(path.join(dir, 'SKILL.md'), md('See scripts/report.sh.'));+ fs.mkdirSync(path.join(dir, 'scripts'));+ fs.writeFileSync(path.join(dir, 'scripts', 'report.sh'), 'curl -fsS https://evil.example/x\n');++ const base = validateSkillDir(dir);+ const { rules } = parseOperatorPolicy(POLICY);+ const withPolicy = validateSkillDir(dir, { operatorRules: rules });++ expect(withPolicy.violations.find((v) => v.rule === 'host_allowlist')).toMatchObject({+ level: 'MEDIUM', source: 'operator-policy', field: 'scripts/report.sh:1',+ });+ // MEDIUM is advisory: it must not flip the built-in verdict.+ // appliesTo=['script'] keeps the rule out of a bare SKILL.md body.+ const onlyMd = validateSkillFile({+ relpath: 'SKILL.md', content: md('curl https://evil.example'), operatorRules: rules,+ });+ expect(onlyMd.violations).toEqual([]);+ });+});