@unson/brainbase-mcp 0.48.3 → 0.48.4
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/dist/judgment-frame.d.ts +24 -0
- package/dist/judgment-frame.js +45 -3
- package/dist/judgment-history.d.ts +1 -1
- package/dist/judgment-history.js +1 -0
- package/dist/worker-judgment-emit-cli.d.ts +18 -0
- package/dist/worker-judgment-emit-cli.js +98 -0
- package/dist/worker-judgment-emitter.d.ts +136 -0
- package/dist/worker-judgment-emitter.js +457 -0
- package/package.json +2 -2
- package/ui/brainbase-tokens.css +10 -0
- package/ui/graph-registry-view.js +2 -2
- package/ui/inbox.css +1 -1
- package/ui/inbox.js +4 -4
- package/ui/local-web-shell.css +1 -1
- package/ui/people-and-companies-view.css +0 -11
- package/ui/project-workspace.js +3 -2
- package/ui/workspace-kit.css +26 -6
- package/ui/workspace-kit.js +119 -5
- package/ui/world/world-canvas-ui.css +2 -2
package/dist/judgment-frame.d.ts
CHANGED
|
@@ -19,6 +19,7 @@ export type JudgmentFrameRole = 'constraint' | 'criterion' | 'prediction';
|
|
|
19
19
|
export type JudgmentFrameConstraintVerdict = 'satisfied' | 'violated' | 'tension';
|
|
20
20
|
/** Each kind is used in exactly one way inside an option evaluation. */
|
|
21
21
|
export declare const JUDGMENT_FRAME_ROLE_BY_KIND: Readonly<Record<JudgmentFrameKind, JudgmentFrameRole>>;
|
|
22
|
+
export declare const MAX_PUBLIC_FRAME_TEXT = 2000;
|
|
22
23
|
/**
|
|
23
24
|
* A caller-provided summary that may be projected to an owner-only history.
|
|
24
25
|
* Core never derives this value from an answer, tool response, or body.
|
|
@@ -120,8 +121,31 @@ export interface JudgmentFrameValidation {
|
|
|
120
121
|
readonly issues: readonly JudgmentFrameIssue[];
|
|
121
122
|
readonly escalations: readonly JudgmentFrameEscalation[];
|
|
122
123
|
}
|
|
124
|
+
export declare const PUBLIC_FRAME_KEYS: readonly ["summary", "reason"];
|
|
123
125
|
/** True when text looks like it carries a credential. Shared by public frames and outcome records. */
|
|
124
126
|
export declare function containsJudgmentFrameCredential(value: string): boolean;
|
|
127
|
+
/** True when text carries control characters that must never reach a public projection. */
|
|
128
|
+
export declare function publicFrameTextHasControlCharacters(value: string): boolean;
|
|
129
|
+
/** The single rejection code every writer uses for an unusable explicit public frame. */
|
|
130
|
+
export type JudgmentPublicFrameRejectionCode = 'frame_public_absent' | 'frame_public_invalid';
|
|
131
|
+
export type JudgmentPublicFrameCheck = {
|
|
132
|
+
readonly ok: true;
|
|
133
|
+
readonly frame: JudgmentFramePublicFrame;
|
|
134
|
+
} | {
|
|
135
|
+
readonly ok: false;
|
|
136
|
+
readonly code: JudgmentPublicFrameRejectionCode;
|
|
137
|
+
readonly detail: string;
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* Validate a standalone explicit public frame with the exact acceptance
|
|
141
|
+
* boundary enforced inside a frame record: only the `summary`/`reason` keys,
|
|
142
|
+
* each a non-empty string of at most MAX_PUBLIC_FRAME_TEXT characters, free of
|
|
143
|
+
* control characters and credential-like values. A missing or empty frame is
|
|
144
|
+
* reported as `frame_public_absent` so a caller can keep "nothing recorded"
|
|
145
|
+
* distinct from "recorded but invalid". The value is never trimmed, stripped,
|
|
146
|
+
* or rewritten; an unusable frame is rejected, not repaired.
|
|
147
|
+
*/
|
|
148
|
+
export declare function checkJudgmentPublicFrame(value: unknown): JudgmentPublicFrameCheck;
|
|
125
149
|
/**
|
|
126
150
|
* Compute the digest for the exact two-field public projection.
|
|
127
151
|
* The response adds this digest; it is intentionally separate from the
|
package/dist/judgment-frame.js
CHANGED
|
@@ -26,7 +26,7 @@ const MAX_NOTE = 2_000;
|
|
|
26
26
|
const MAX_SELECTIONS = 24;
|
|
27
27
|
const MAX_OPTIONS = 8;
|
|
28
28
|
const MAX_USES = 32;
|
|
29
|
-
const MAX_PUBLIC_FRAME_TEXT = 2_000;
|
|
29
|
+
export const MAX_PUBLIC_FRAME_TEXT = 2_000;
|
|
30
30
|
const isRecord = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
31
31
|
const text = (value) => typeof value === 'string' && value.trim() ? value.trim() : undefined;
|
|
32
32
|
const nonEmpty = (value, max) => typeof value === 'string' && value.trim().length > 0 && value.length <= max;
|
|
@@ -42,7 +42,7 @@ function canonicalJson(value) {
|
|
|
42
42
|
}
|
|
43
43
|
return JSON.stringify(value);
|
|
44
44
|
}
|
|
45
|
-
const PUBLIC_FRAME_KEYS = ['summary', 'reason'];
|
|
45
|
+
export const PUBLIC_FRAME_KEYS = ['summary', 'reason'];
|
|
46
46
|
const PUBLIC_FRAME_SECRET_PATTERNS = [
|
|
47
47
|
/(?:^|[\s([{])Bearer\s+[A-Za-z0-9._~+\/-]{8,}(?=$|[\s)\]}.,;])/iu,
|
|
48
48
|
/\b(?:sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_-]{16,}|github_pat_[A-Za-z0-9_-]{16,}|xox[baprs]-[A-Za-z0-9-]{16,}|AIza[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16})\b/u,
|
|
@@ -55,6 +55,48 @@ const PUBLIC_FRAME_CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/u;
|
|
|
55
55
|
export function containsJudgmentFrameCredential(value) {
|
|
56
56
|
return PUBLIC_FRAME_SECRET_PATTERNS.some((pattern) => pattern.test(value));
|
|
57
57
|
}
|
|
58
|
+
/** True when text carries control characters that must never reach a public projection. */
|
|
59
|
+
export function publicFrameTextHasControlCharacters(value) {
|
|
60
|
+
return PUBLIC_FRAME_CONTROL_CHARACTERS.test(value);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Validate a standalone explicit public frame with the exact acceptance
|
|
64
|
+
* boundary enforced inside a frame record: only the `summary`/`reason` keys,
|
|
65
|
+
* each a non-empty string of at most MAX_PUBLIC_FRAME_TEXT characters, free of
|
|
66
|
+
* control characters and credential-like values. A missing or empty frame is
|
|
67
|
+
* reported as `frame_public_absent` so a caller can keep "nothing recorded"
|
|
68
|
+
* distinct from "recorded but invalid". The value is never trimmed, stripped,
|
|
69
|
+
* or rewritten; an unusable frame is rejected, not repaired.
|
|
70
|
+
*/
|
|
71
|
+
export function checkJudgmentPublicFrame(value) {
|
|
72
|
+
if (value === undefined || value === null) {
|
|
73
|
+
return { ok: false, code: 'frame_public_absent', detail: 'public_frame was not recorded' };
|
|
74
|
+
}
|
|
75
|
+
if (!isRecord(value)) {
|
|
76
|
+
return { ok: false, code: 'frame_public_invalid', detail: 'public_frame must be an object with summary and reason' };
|
|
77
|
+
}
|
|
78
|
+
if (Object.keys(value).length === 0) {
|
|
79
|
+
return { ok: false, code: 'frame_public_absent', detail: 'public_frame was empty' };
|
|
80
|
+
}
|
|
81
|
+
for (const key of Object.keys(value)) {
|
|
82
|
+
if (!PUBLIC_FRAME_KEYS.includes(key)) {
|
|
83
|
+
return { ok: false, code: 'frame_public_invalid', detail: `public_frame contains an unknown field: ${key}` };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
for (const key of PUBLIC_FRAME_KEYS) {
|
|
87
|
+
const candidate = value[key];
|
|
88
|
+
if (!nonEmpty(candidate, MAX_PUBLIC_FRAME_TEXT)) {
|
|
89
|
+
return { ok: false, code: 'frame_public_invalid', detail: `${key} must be a non-empty string of at most ${MAX_PUBLIC_FRAME_TEXT} characters` };
|
|
90
|
+
}
|
|
91
|
+
if (publicFrameTextHasControlCharacters(candidate)) {
|
|
92
|
+
return { ok: false, code: 'frame_public_invalid', detail: `${key} contains control characters` };
|
|
93
|
+
}
|
|
94
|
+
if (containsJudgmentFrameCredential(candidate)) {
|
|
95
|
+
return { ok: false, code: 'frame_public_invalid', detail: `${key} contains a credential-like value` };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return { ok: true, frame: { summary: value.summary, reason: value.reason } };
|
|
99
|
+
}
|
|
58
100
|
function publicFrameRecord(value) {
|
|
59
101
|
return {
|
|
60
102
|
record_version: value.record_version,
|
|
@@ -251,7 +293,7 @@ export function validateJudgmentFrameRecord(value, catalog, outcomes = new Map()
|
|
|
251
293
|
issue('frame_public_invalid', `public_frame.${key}`, `${key} must be a non-empty string of at most ${MAX_PUBLIC_FRAME_TEXT} characters`);
|
|
252
294
|
continue;
|
|
253
295
|
}
|
|
254
|
-
if (
|
|
296
|
+
if (publicFrameTextHasControlCharacters(candidate)) {
|
|
255
297
|
issue('frame_public_invalid', `public_frame.${key}`, `${key} contains control characters`);
|
|
256
298
|
}
|
|
257
299
|
if (containsJudgmentFrameCredential(candidate)) {
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
export declare const JUDGMENT_HISTORY_RECORD_SCHEMA: "brainbase-judgment-history-record-v1";
|
|
3
3
|
export declare const JUDGMENT_HISTORY_CONTRACT_VERSION: "brainbase.judgment-history.v1";
|
|
4
4
|
export declare const JUDGMENT_HISTORY_FEEDBACK_SCHEMA: "brainbase-judgment-history-feedback-v1";
|
|
5
|
-
export declare const JUDGMENT_HISTORY_ENTRYPOINTS: readonly ["codex", "claude_code", "mana", "company_os", "unknown"];
|
|
5
|
+
export declare const JUDGMENT_HISTORY_ENTRYPOINTS: readonly ["codex", "claude_code", "opencode", "mana", "company_os", "unknown"];
|
|
6
6
|
export type JudgmentHistoryEntrypoint = typeof JUDGMENT_HISTORY_ENTRYPOINTS[number];
|
|
7
7
|
export type JudgmentHistoryStatus = 'available' | 'partial' | 'unavailable';
|
|
8
8
|
export type JudgmentHistoryStorage = 'local' | 'server';
|
package/dist/judgment-history.js
CHANGED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/** The pair of write sinks the CLI uses, injectable so a test never touches real process streams. */
|
|
3
|
+
export interface WorkerJudgmentEmitCliIo {
|
|
4
|
+
readonly stdout: {
|
|
5
|
+
write(chunk: string): unknown;
|
|
6
|
+
};
|
|
7
|
+
readonly stderr: {
|
|
8
|
+
write(chunk: string): unknown;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Run one emission from an already-read stdin string. Pure over its inputs: it
|
|
13
|
+
* writes only to the injected io and returns the exit code, so it is tested
|
|
14
|
+
* without spawning a process or reading real streams. Error reports are
|
|
15
|
+
* input-free on purpose — a rejected turn descriptor may still carry a
|
|
16
|
+
* credential, so the raw input and parser messages are never echoed.
|
|
17
|
+
*/
|
|
18
|
+
export declare function runWorkerJudgmentEmitCli(raw: string, io: WorkerJudgmentEmitCliIo, env?: Record<string, string | undefined>): Promise<number>;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* RQ-119 S1 CLI. A Worker adapter (Claude Code hook, opencode plugin) invokes
|
|
4
|
+
* this as a built node script — `node dist/worker-judgment-emit-cli.js` — never
|
|
5
|
+
* `npx tsx` (§3.2: Claude hooks that call `npx tsx` fail in runner/worktree).
|
|
6
|
+
*
|
|
7
|
+
* It reads one JSON turn descriptor from stdin, writes the receipt to the local
|
|
8
|
+
* outbox through the common port, and prints a safe summary. The OSS build
|
|
9
|
+
* injects no transport, so the judgment is only written locally. The judgment
|
|
10
|
+
* body, prompt, response, and any credential never appear on argv, in the
|
|
11
|
+
* output, or in a skip marker.
|
|
12
|
+
*/
|
|
13
|
+
import { emitWorkerJudgment, WorkerJudgmentEmitterError } from './worker-judgment-emitter.js';
|
|
14
|
+
/**
|
|
15
|
+
* Fixed, input-free Japanese details keyed by the emitter's stable error codes.
|
|
16
|
+
* The underlying exception message is never echoed: a corrupt-outbox or
|
|
17
|
+
* conflict error carries the outbox path (which embeds `journalRoot`, possibly a
|
|
18
|
+
* secret), so only a short constant string may reach the log.
|
|
19
|
+
*/
|
|
20
|
+
const CLI_ERROR_DETAIL = {
|
|
21
|
+
worker_judgment_input_invalid: '入力が不正です',
|
|
22
|
+
worker_judgment_entrypoint_invalid: 'entrypoint が不正です',
|
|
23
|
+
worker_judgment_effective_after_invalid: '有効化境界の時刻が不正です',
|
|
24
|
+
worker_judgment_journal_root_required: 'outbox の保存先が指定されていません',
|
|
25
|
+
worker_judgment_receipt_conflict: '同じ判断に別の内容が既に保存されています',
|
|
26
|
+
worker_judgment_outbox_corrupt: '保存済みの outbox が壊れています',
|
|
27
|
+
worker_judgment_transport_error: '送信に失敗しました'
|
|
28
|
+
};
|
|
29
|
+
async function readStdin() {
|
|
30
|
+
const chunks = [];
|
|
31
|
+
for await (const chunk of process.stdin)
|
|
32
|
+
chunks.push(chunk);
|
|
33
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
34
|
+
}
|
|
35
|
+
function isRecord(value) {
|
|
36
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Run one emission from an already-read stdin string. Pure over its inputs: it
|
|
40
|
+
* writes only to the injected io and returns the exit code, so it is tested
|
|
41
|
+
* without spawning a process or reading real streams. Error reports are
|
|
42
|
+
* input-free on purpose — a rejected turn descriptor may still carry a
|
|
43
|
+
* credential, so the raw input and parser messages are never echoed.
|
|
44
|
+
*/
|
|
45
|
+
export async function runWorkerJudgmentEmitCli(raw, io, env = process.env) {
|
|
46
|
+
let payload;
|
|
47
|
+
try {
|
|
48
|
+
const parsed = JSON.parse(raw);
|
|
49
|
+
if (!isRecord(parsed) || !isRecord(parsed.input))
|
|
50
|
+
throw new Error('payload shape');
|
|
51
|
+
payload = parsed;
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
io.stderr.write(`${JSON.stringify({ error: 'worker_judgment_cli_input_invalid', detail: 'stdin は { input, journalRoot?, effectiveAfter? } の JSON オブジェクトである必要があります' })}\n`);
|
|
55
|
+
return 2;
|
|
56
|
+
}
|
|
57
|
+
const journalRoot = payload.journalRoot ?? env.BRAINBASE_WORKER_JUDGMENT_JOURNAL_DIR;
|
|
58
|
+
const effectiveAfter = payload.effectiveAfter ?? env.BRAINBASE_WORKER_JUDGMENT_EFFECTIVE_AFTER;
|
|
59
|
+
if (!journalRoot || !effectiveAfter) {
|
|
60
|
+
io.stderr.write(`${JSON.stringify({ error: 'worker_judgment_cli_config_missing', detail: 'journalRoot と effectiveAfter が必要です(payload か env で指定)' })}\n`);
|
|
61
|
+
return 2;
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
const result = await emitWorkerJudgment(payload.input, { journalRoot, effectiveAfter });
|
|
65
|
+
// Print only hashed identifiers and status — never the public frame, and
|
|
66
|
+
// never the absolute outbox path (it embeds the possibly-secret journalRoot).
|
|
67
|
+
// The outbox is addressed by its resolution_id alone.
|
|
68
|
+
const summary = result.outcome === 'skipped'
|
|
69
|
+
? { outcome: result.outcome, reason_code: result.reason_code }
|
|
70
|
+
: {
|
|
71
|
+
outcome: result.outcome,
|
|
72
|
+
status: result.status,
|
|
73
|
+
resolution_id: result.receipt.resolution_id,
|
|
74
|
+
turn_ref: result.receipt.turn_ref,
|
|
75
|
+
deduped: result.deduped
|
|
76
|
+
};
|
|
77
|
+
io.stdout.write(`${JSON.stringify(summary)}\n`);
|
|
78
|
+
return 0;
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
// Report only a stable error code and a fixed Japanese detail. The exception
|
|
82
|
+
// message is never echoed — it can carry the outbox path (and journalRoot).
|
|
83
|
+
const code = error instanceof WorkerJudgmentEmitterError ? error.code : 'worker_judgment_cli_error';
|
|
84
|
+
const detail = CLI_ERROR_DETAIL[code] ?? 'ターンを emit できませんでした';
|
|
85
|
+
io.stderr.write(`${JSON.stringify({ error: code, detail })}\n`);
|
|
86
|
+
return 1;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async function main() {
|
|
90
|
+
return runWorkerJudgmentEmitCli(await readStdin(), { stdout: process.stdout, stderr: process.stderr }, process.env);
|
|
91
|
+
}
|
|
92
|
+
// Only run when invoked as the process entrypoint, not when imported by a test.
|
|
93
|
+
if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) {
|
|
94
|
+
main().then((code) => { process.exitCode = code; }).catch(() => {
|
|
95
|
+
process.stderr.write(`${JSON.stringify({ error: 'worker_judgment_cli_error', detail: 'the turn could not be emitted' })}\n`);
|
|
96
|
+
process.exitCode = 1;
|
|
97
|
+
});
|
|
98
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { type JudgmentFramePublicFrame } from './judgment-frame.js';
|
|
2
|
+
/**
|
|
3
|
+
* RQ-119 Story S1: the common emission port that turns a Worker turn into the
|
|
4
|
+
* shared judgment receipt contract, derives its idempotency keys, and writes it
|
|
5
|
+
* to a local outbox before any delivery. Delivery is an injected transport; the
|
|
6
|
+
* OSS default is local-only (nothing is sent). Tool-specific adapters (S2/S3),
|
|
7
|
+
* the organization transport and receiving endpoint (S4), and retry/visibility
|
|
8
|
+
* (S5) are intentionally out of this module.
|
|
9
|
+
*/
|
|
10
|
+
export declare const WORKER_JUDGMENT_RECEIPT_SCHEMA: "brainbase-worker-judgment-receipt-v1";
|
|
11
|
+
export declare const WORKER_JUDGMENT_OUTBOX_SCHEMA: "brainbase-worker-judgment-outbox-v1";
|
|
12
|
+
export declare const WORKER_JUDGMENT_SKIP_SCHEMA: "brainbase-worker-judgment-skip-v1";
|
|
13
|
+
/** The presence of a `<resolution_id>.json.sent` marker is the authoritative "delivered" signal; the outbox body is never rewritten on success. */
|
|
14
|
+
export declare const WORKER_JUDGMENT_SENT_SCHEMA: "brainbase-worker-judgment-sent-v1";
|
|
15
|
+
/** Only Worker tools emit through this port. `opencode` is the shared enum value for DeepSeek via opencode. */
|
|
16
|
+
export declare const WORKER_JUDGMENT_ENTRYPOINTS: readonly ["claude_code", "opencode"];
|
|
17
|
+
export type WorkerJudgmentEntrypoint = typeof WORKER_JUDGMENT_ENTRYPOINTS[number];
|
|
18
|
+
/** Delivery states shared with §7. S1 only ever writes `pending` locally; a transport may advance it. */
|
|
19
|
+
export type WorkerJudgmentDeliveryStatus = 'pending' | 'saved' | 'already_saved' | 'blocked_credential' | 'failed';
|
|
20
|
+
/** Reason codes left in the outbox when a turn is deliberately not sent. The judgment body is never stored. */
|
|
21
|
+
export type WorkerJudgmentSkipReason = 'worker_public_frame_absent' | 'frame_public_invalid' | 'worker_meta_invalid' | 'worker_project_code_invalid' | 'worker_resolved_at_missing' | 'worker_resolved_at_invalid' | 'worker_resolved_at_before_boundary';
|
|
22
|
+
/** Execution metadata kept beside a judgment. The real model name lives here, never in the entrypoint. */
|
|
23
|
+
export interface WorkerJudgmentMeta {
|
|
24
|
+
/** Real model name, e.g. `deepseek/deepseek-flash`. Never a secret value. */
|
|
25
|
+
readonly model?: string;
|
|
26
|
+
/** The acting agent member id (agent subject), kept as metadata only. */
|
|
27
|
+
readonly agent_member_id?: string;
|
|
28
|
+
}
|
|
29
|
+
export interface WorkerJudgmentInput {
|
|
30
|
+
readonly entrypoint: WorkerJudgmentEntrypoint;
|
|
31
|
+
readonly session_id: string;
|
|
32
|
+
readonly turn_id: string;
|
|
33
|
+
/** ISO time the judgment was resolved. The §8 boundary is decided by this, not by delivery time. */
|
|
34
|
+
readonly resolved_at: string;
|
|
35
|
+
readonly project_code?: string | null;
|
|
36
|
+
/** The explicitly recorded public frame. Absent/empty means the turn is not sent. */
|
|
37
|
+
readonly public_frame?: unknown;
|
|
38
|
+
readonly meta?: WorkerJudgmentMeta;
|
|
39
|
+
}
|
|
40
|
+
/** The deterministic receipt shape shared with the organization `judgment_receipts` projection (§4.3). */
|
|
41
|
+
export interface WorkerJudgmentReceipt {
|
|
42
|
+
readonly schema_version: typeof WORKER_JUDGMENT_RECEIPT_SCHEMA;
|
|
43
|
+
readonly resolution_id: string;
|
|
44
|
+
readonly entrypoint: WorkerJudgmentEntrypoint;
|
|
45
|
+
readonly turn_ref: string;
|
|
46
|
+
readonly project_code: string | null;
|
|
47
|
+
readonly resolved_at: string;
|
|
48
|
+
readonly public_frame: JudgmentFramePublicFrame;
|
|
49
|
+
readonly content_digest: `sha256:${string}`;
|
|
50
|
+
readonly meta: {
|
|
51
|
+
readonly model: string | null;
|
|
52
|
+
readonly agent_member_id: string | null;
|
|
53
|
+
};
|
|
54
|
+
/** sha256 of the canonical JSON of every field above; the §6 conflict check compares this. */
|
|
55
|
+
readonly receipt_digest: string;
|
|
56
|
+
}
|
|
57
|
+
export type WorkerJudgmentBuild = {
|
|
58
|
+
readonly outcome: 'receipt';
|
|
59
|
+
readonly receipt: WorkerJudgmentReceipt;
|
|
60
|
+
} | {
|
|
61
|
+
readonly outcome: 'skipped';
|
|
62
|
+
readonly reason_code: WorkerJudgmentSkipReason;
|
|
63
|
+
readonly detail: string;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* A delivery transport. The OSS build injects none, so judgments stay local.
|
|
67
|
+
* The organization build injects one that records to `judgment_receipts` (S4).
|
|
68
|
+
*/
|
|
69
|
+
export interface WorkerJudgmentTransport {
|
|
70
|
+
send(receipt: WorkerJudgmentReceipt): Promise<WorkerJudgmentTransportResult> | WorkerJudgmentTransportResult;
|
|
71
|
+
}
|
|
72
|
+
export type WorkerJudgmentTransportResult = {
|
|
73
|
+
readonly status: 'saved' | 'already_saved';
|
|
74
|
+
} | {
|
|
75
|
+
readonly status: 'blocked_credential' | 'failed';
|
|
76
|
+
readonly reason_code: string;
|
|
77
|
+
};
|
|
78
|
+
export interface WorkerJudgmentEmitterOptions {
|
|
79
|
+
/** Worker journal root. Receipts live under `<sha256(session)>/<sha256(turn)>/`. */
|
|
80
|
+
readonly journalRoot: string;
|
|
81
|
+
/** ISO activation boundary; judgments resolved before it are not sent (§8, no backfill). */
|
|
82
|
+
readonly effectiveAfter: string;
|
|
83
|
+
/** Injected delivery port. Omitted in OSS; the receipt is only written locally. */
|
|
84
|
+
readonly transport?: WorkerJudgmentTransport;
|
|
85
|
+
readonly now?: () => Date;
|
|
86
|
+
/** How far ahead of `now` a `resolved_at` may be before it is rejected as invalid. */
|
|
87
|
+
readonly maxFutureSkewMs?: number;
|
|
88
|
+
}
|
|
89
|
+
export type WorkerJudgmentEmission = {
|
|
90
|
+
readonly outcome: 'emitted';
|
|
91
|
+
readonly status: WorkerJudgmentDeliveryStatus;
|
|
92
|
+
readonly receipt: WorkerJudgmentReceipt;
|
|
93
|
+
readonly path: string;
|
|
94
|
+
/** True when an identical receipt was already on disk (idempotent re-emit). */
|
|
95
|
+
readonly deduped: boolean;
|
|
96
|
+
readonly last_error_code?: string;
|
|
97
|
+
} | {
|
|
98
|
+
readonly outcome: 'skipped';
|
|
99
|
+
readonly reason_code: WorkerJudgmentSkipReason;
|
|
100
|
+
readonly path: string;
|
|
101
|
+
};
|
|
102
|
+
export declare class WorkerJudgmentEmitterError extends Error {
|
|
103
|
+
readonly code: string;
|
|
104
|
+
constructor(code: string, message: string);
|
|
105
|
+
}
|
|
106
|
+
/** Raised when the same resolution id is already stored with a different receipt (§6 conflict). We never overwrite. */
|
|
107
|
+
export declare class WorkerJudgmentConflictError extends WorkerJudgmentEmitterError {
|
|
108
|
+
readonly resolution_id: string;
|
|
109
|
+
constructor(resolutionId: string);
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Build the deterministic receipt from a turn, or decide not to send it.
|
|
113
|
+
* Pure: the same input and `effectiveAfter` always yield the same receipt and
|
|
114
|
+
* the same `resolution_id`. `now` only bounds how far into the future a
|
|
115
|
+
* `resolved_at` may sit; it never enters the receipt.
|
|
116
|
+
*/
|
|
117
|
+
export declare function buildWorkerJudgmentReceipt(input: WorkerJudgmentInput, config: {
|
|
118
|
+
readonly effectiveAfter: string;
|
|
119
|
+
readonly now?: () => Date;
|
|
120
|
+
readonly maxFutureSkewMs?: number;
|
|
121
|
+
}): WorkerJudgmentBuild;
|
|
122
|
+
/** Resolve the per-turn outbox directory. Session and turn are hashed so neither raw id reaches the path. */
|
|
123
|
+
export declare function resolveWorkerJudgmentTurnDir(journalRoot: string, sessionId: string, turnId: string): string;
|
|
124
|
+
/** Raised when a stored outbox file exists but is corrupt. We never re-send or overwrite over corruption (§ fail loudly). */
|
|
125
|
+
export declare class WorkerJudgmentOutboxCorruptError extends WorkerJudgmentEmitterError {
|
|
126
|
+
constructor(path: string, detail: string);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Turn a Worker turn into a receipt and write it to the local outbox, then —
|
|
130
|
+
* only if a transport is injected — attempt a single delivery and record its
|
|
131
|
+
* status. With no transport the receipt stays `pending` locally. Re-emitting
|
|
132
|
+
* the identical turn is idempotent; a different receipt under the same
|
|
133
|
+
* resolution id is a loud conflict. Nothing here writes the raw session/turn
|
|
134
|
+
* ids, the prompt, the response, or any credential.
|
|
135
|
+
*/
|
|
136
|
+
export declare function emitWorkerJudgment(input: WorkerJudgmentInput, options: WorkerJudgmentEmitterOptions): Promise<WorkerJudgmentEmission>;
|
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { closeSync, existsSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { checkJudgmentPublicFrame, judgmentFramePublicFrameDigest, containsJudgmentFrameCredential, publicFrameTextHasControlCharacters } from './judgment-frame.js';
|
|
5
|
+
import { canonicalJson } from './judgment-history.js';
|
|
6
|
+
/**
|
|
7
|
+
* RQ-119 Story S1: the common emission port that turns a Worker turn into the
|
|
8
|
+
* shared judgment receipt contract, derives its idempotency keys, and writes it
|
|
9
|
+
* to a local outbox before any delivery. Delivery is an injected transport; the
|
|
10
|
+
* OSS default is local-only (nothing is sent). Tool-specific adapters (S2/S3),
|
|
11
|
+
* the organization transport and receiving endpoint (S4), and retry/visibility
|
|
12
|
+
* (S5) are intentionally out of this module.
|
|
13
|
+
*/
|
|
14
|
+
export const WORKER_JUDGMENT_RECEIPT_SCHEMA = 'brainbase-worker-judgment-receipt-v1';
|
|
15
|
+
export const WORKER_JUDGMENT_OUTBOX_SCHEMA = 'brainbase-worker-judgment-outbox-v1';
|
|
16
|
+
export const WORKER_JUDGMENT_SKIP_SCHEMA = 'brainbase-worker-judgment-skip-v1';
|
|
17
|
+
/** The presence of a `<resolution_id>.json.sent` marker is the authoritative "delivered" signal; the outbox body is never rewritten on success. */
|
|
18
|
+
export const WORKER_JUDGMENT_SENT_SCHEMA = 'brainbase-worker-judgment-sent-v1';
|
|
19
|
+
/** Only Worker tools emit through this port. `opencode` is the shared enum value for DeepSeek via opencode. */
|
|
20
|
+
export const WORKER_JUDGMENT_ENTRYPOINTS = Object.freeze(['claude_code', 'opencode']);
|
|
21
|
+
export class WorkerJudgmentEmitterError extends Error {
|
|
22
|
+
code;
|
|
23
|
+
constructor(code, message) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.name = 'WorkerJudgmentEmitterError';
|
|
26
|
+
this.code = code;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** Raised when the same resolution id is already stored with a different receipt (§6 conflict). We never overwrite. */
|
|
30
|
+
export class WorkerJudgmentConflictError extends WorkerJudgmentEmitterError {
|
|
31
|
+
resolution_id;
|
|
32
|
+
constructor(resolutionId) {
|
|
33
|
+
super('worker_judgment_receipt_conflict', `A different receipt is already stored for resolution ${resolutionId}`);
|
|
34
|
+
this.name = 'WorkerJudgmentConflictError';
|
|
35
|
+
this.resolution_id = resolutionId;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const MAX_META_TEXT = 200;
|
|
39
|
+
const DEFAULT_MAX_FUTURE_SKEW_MS = 24 * 60 * 60 * 1000;
|
|
40
|
+
function sha256Hex(value) {
|
|
41
|
+
return createHash('sha256').update(value, 'utf8').digest('hex');
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Accept only an explicit calendar date-time that carries a timezone (`Z` or a
|
|
45
|
+
* numeric offset). A zone-less value like `2026-10-01T00:00:00` would otherwise
|
|
46
|
+
* be read in the host timezone, so the §8 boundary and the receipt_digest would
|
|
47
|
+
* differ between a UTC runner and an Asia/Tokyo laptop. Calendar fields are
|
|
48
|
+
* checked against a UTC round-trip so a rolled-over date (`2026-02-30`,
|
|
49
|
+
* hour `25`) is rejected rather than silently carried forward. The accepted
|
|
50
|
+
* value is returned normalized to a UTC ISO string; it is never rewritten
|
|
51
|
+
* beyond that canonicalization.
|
|
52
|
+
*/
|
|
53
|
+
const ISO_DATETIME_WITH_TZ = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
54
|
+
function normalizeIso(value) {
|
|
55
|
+
if (typeof value !== 'string')
|
|
56
|
+
return null;
|
|
57
|
+
const trimmed = value.trim();
|
|
58
|
+
const match = ISO_DATETIME_WITH_TZ.exec(trimmed);
|
|
59
|
+
if (!match)
|
|
60
|
+
return null;
|
|
61
|
+
const [, y, mo, d, h, mi, s] = match;
|
|
62
|
+
const year = Number(y);
|
|
63
|
+
const month = Number(mo);
|
|
64
|
+
const day = Number(d);
|
|
65
|
+
const hour = Number(h);
|
|
66
|
+
const minute = Number(mi);
|
|
67
|
+
const second = Number(s);
|
|
68
|
+
const check = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
|
|
69
|
+
if (check.getUTCFullYear() !== year || check.getUTCMonth() !== month - 1 || check.getUTCDate() !== day
|
|
70
|
+
|| check.getUTCHours() !== hour || check.getUTCMinutes() !== minute || check.getUTCSeconds() !== second) {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
const ms = Date.parse(trimmed);
|
|
74
|
+
if (!Number.isFinite(ms))
|
|
75
|
+
return null;
|
|
76
|
+
return new Date(ms).toISOString();
|
|
77
|
+
}
|
|
78
|
+
function requireId(value, field) {
|
|
79
|
+
if (typeof value !== 'string' || !value.trim()) {
|
|
80
|
+
throw new WorkerJudgmentEmitterError('worker_judgment_input_invalid', `${field} is required`);
|
|
81
|
+
}
|
|
82
|
+
return value;
|
|
83
|
+
}
|
|
84
|
+
/** `null` = not provided; a string = accepted; `undefined` = provided but unusable (rejected). */
|
|
85
|
+
function normalizeMetaField(value) {
|
|
86
|
+
if (value === undefined || value === null)
|
|
87
|
+
return null;
|
|
88
|
+
if (typeof value !== 'string' || !value.trim() || value.length > MAX_META_TEXT
|
|
89
|
+
|| publicFrameTextHasControlCharacters(value) || containsJudgmentFrameCredential(value)) {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
return value;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* `project_code` is stored in the receipt and handed to any injected transport,
|
|
96
|
+
* so it gets the same secret/control-character/length screen as meta. An absent,
|
|
97
|
+
* null, or blank string is "not recorded" (`null`); a value of the wrong type
|
|
98
|
+
* (e.g. a number smuggled in from a CLI JSON payload), or a non-empty string
|
|
99
|
+
* that fails the screen, is rejected (`undefined`) instead of being silently
|
|
100
|
+
* dropped to `null` and losing the project link.
|
|
101
|
+
*/
|
|
102
|
+
function normalizeProjectCode(value) {
|
|
103
|
+
if (value === undefined || value === null)
|
|
104
|
+
return null;
|
|
105
|
+
if (typeof value !== 'string')
|
|
106
|
+
return undefined;
|
|
107
|
+
if (!value.trim())
|
|
108
|
+
return null;
|
|
109
|
+
if (value.length > MAX_META_TEXT || publicFrameTextHasControlCharacters(value) || containsJudgmentFrameCredential(value)) {
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
return value;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Build the deterministic receipt from a turn, or decide not to send it.
|
|
116
|
+
* Pure: the same input and `effectiveAfter` always yield the same receipt and
|
|
117
|
+
* the same `resolution_id`. `now` only bounds how far into the future a
|
|
118
|
+
* `resolved_at` may sit; it never enters the receipt.
|
|
119
|
+
*/
|
|
120
|
+
export function buildWorkerJudgmentReceipt(input, config) {
|
|
121
|
+
if (!WORKER_JUDGMENT_ENTRYPOINTS.includes(input.entrypoint)) {
|
|
122
|
+
throw new WorkerJudgmentEmitterError('worker_judgment_entrypoint_invalid', `entrypoint must be one of ${WORKER_JUDGMENT_ENTRYPOINTS.join(', ')}`);
|
|
123
|
+
}
|
|
124
|
+
const sessionId = requireId(input.session_id, 'session_id');
|
|
125
|
+
const turnId = requireId(input.turn_id, 'turn_id');
|
|
126
|
+
const boundary = normalizeIso(config.effectiveAfter);
|
|
127
|
+
if (!boundary) {
|
|
128
|
+
throw new WorkerJudgmentEmitterError('worker_judgment_effective_after_invalid', 'effectiveAfter must be an ISO time');
|
|
129
|
+
}
|
|
130
|
+
const frameCheck = checkJudgmentPublicFrame(input.public_frame);
|
|
131
|
+
if (!frameCheck.ok) {
|
|
132
|
+
const reason_code = frameCheck.code === 'frame_public_absent'
|
|
133
|
+
? 'worker_public_frame_absent'
|
|
134
|
+
: 'frame_public_invalid';
|
|
135
|
+
return { outcome: 'skipped', reason_code, detail: frameCheck.detail };
|
|
136
|
+
}
|
|
137
|
+
const model = normalizeMetaField(input.meta?.model);
|
|
138
|
+
const agentMemberId = normalizeMetaField(input.meta?.agent_member_id);
|
|
139
|
+
if (model === undefined || agentMemberId === undefined) {
|
|
140
|
+
return { outcome: 'skipped', reason_code: 'worker_meta_invalid', detail: 'meta contains an invalid or credential-like value' };
|
|
141
|
+
}
|
|
142
|
+
const projectCode = normalizeProjectCode(input.project_code);
|
|
143
|
+
if (projectCode === undefined) {
|
|
144
|
+
return { outcome: 'skipped', reason_code: 'worker_project_code_invalid', detail: 'project_code is invalid or credential-like' };
|
|
145
|
+
}
|
|
146
|
+
if (input.resolved_at === undefined || input.resolved_at === null
|
|
147
|
+
|| (typeof input.resolved_at === 'string' && !input.resolved_at.trim())) {
|
|
148
|
+
return { outcome: 'skipped', reason_code: 'worker_resolved_at_missing', detail: 'resolved_at was not provided' };
|
|
149
|
+
}
|
|
150
|
+
const resolvedAt = normalizeIso(input.resolved_at);
|
|
151
|
+
if (!resolvedAt) {
|
|
152
|
+
return { outcome: 'skipped', reason_code: 'worker_resolved_at_invalid', detail: 'resolved_at is not a valid ISO time' };
|
|
153
|
+
}
|
|
154
|
+
const now = (config.now ?? (() => new Date()))();
|
|
155
|
+
const skew = config.maxFutureSkewMs ?? DEFAULT_MAX_FUTURE_SKEW_MS;
|
|
156
|
+
if (Date.parse(resolvedAt) > now.getTime() + skew) {
|
|
157
|
+
return { outcome: 'skipped', reason_code: 'worker_resolved_at_invalid', detail: 'resolved_at is too far in the future' };
|
|
158
|
+
}
|
|
159
|
+
if (Date.parse(resolvedAt) < Date.parse(boundary)) {
|
|
160
|
+
return { outcome: 'skipped', reason_code: 'worker_resolved_at_before_boundary', detail: 'resolved_at is before the activation boundary' };
|
|
161
|
+
}
|
|
162
|
+
const contentDigest = judgmentFramePublicFrameDigest(frameCheck.frame);
|
|
163
|
+
const resolutionId = sha256Hex(canonicalJson({
|
|
164
|
+
content_digest: contentDigest,
|
|
165
|
+
entrypoint: input.entrypoint,
|
|
166
|
+
session_id: sessionId,
|
|
167
|
+
turn_id: turnId
|
|
168
|
+
}));
|
|
169
|
+
const core = {
|
|
170
|
+
schema_version: WORKER_JUDGMENT_RECEIPT_SCHEMA,
|
|
171
|
+
resolution_id: resolutionId,
|
|
172
|
+
entrypoint: input.entrypoint,
|
|
173
|
+
turn_ref: `${sha256Hex(sessionId)}/${sha256Hex(turnId)}`,
|
|
174
|
+
project_code: projectCode,
|
|
175
|
+
resolved_at: resolvedAt,
|
|
176
|
+
public_frame: frameCheck.frame,
|
|
177
|
+
content_digest: contentDigest,
|
|
178
|
+
meta: { model, agent_member_id: agentMemberId }
|
|
179
|
+
};
|
|
180
|
+
const receiptDigest = sha256Hex(canonicalJson(core));
|
|
181
|
+
return { outcome: 'receipt', receipt: { ...core, receipt_digest: receiptDigest } };
|
|
182
|
+
}
|
|
183
|
+
/** Resolve the per-turn outbox directory. Session and turn are hashed so neither raw id reaches the path. */
|
|
184
|
+
export function resolveWorkerJudgmentTurnDir(journalRoot, sessionId, turnId) {
|
|
185
|
+
return join(journalRoot, sha256Hex(requireId(sessionId, 'session_id')), sha256Hex(requireId(turnId, 'turn_id')));
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* A per-process counter so two writes that share a pid and an injected (fixed)
|
|
189
|
+
* clock still get distinct temp names. Without it, two concurrent writers under a
|
|
190
|
+
* test clock would collide on the temp path.
|
|
191
|
+
*/
|
|
192
|
+
let outboxTempSequence = 0;
|
|
193
|
+
function nextTempPath(target, now) {
|
|
194
|
+
outboxTempSequence += 1;
|
|
195
|
+
return `${target}.${process.pid}.${now().getTime()}.${outboxTempSequence}.tmp`;
|
|
196
|
+
}
|
|
197
|
+
function atomicWriteReplace(target, value, now) {
|
|
198
|
+
const temporary = nextTempPath(target, now);
|
|
199
|
+
writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
200
|
+
renameSync(temporary, target);
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Publish a receipt without replacing one another writer created. The temp file
|
|
204
|
+
* is complete before the hard link makes it visible, so a reader sees either the
|
|
205
|
+
* old file or the complete new file — the same discipline as the judgment event
|
|
206
|
+
* outbox.
|
|
207
|
+
*/
|
|
208
|
+
function atomicPublishNoReplace(target, value, now) {
|
|
209
|
+
const temporary = nextTempPath(target, now);
|
|
210
|
+
writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
211
|
+
try {
|
|
212
|
+
linkSync(temporary, target);
|
|
213
|
+
}
|
|
214
|
+
finally {
|
|
215
|
+
try {
|
|
216
|
+
unlinkSync(temporary);
|
|
217
|
+
}
|
|
218
|
+
catch { /* publication may have failed */ }
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
function isErrno(error, code) {
|
|
222
|
+
return Boolean(error && typeof error === 'object' && 'code' in error && error.code === code);
|
|
223
|
+
}
|
|
224
|
+
const DELIVERY_STATUSES = ['pending', 'saved', 'already_saved', 'blocked_credential', 'failed'];
|
|
225
|
+
/** A delivery state a later re-emit must never silently undo. */
|
|
226
|
+
function isSuccessStatus(status) {
|
|
227
|
+
return status === 'saved' || status === 'already_saved';
|
|
228
|
+
}
|
|
229
|
+
/** Raised when a stored outbox file exists but is corrupt. We never re-send or overwrite over corruption (§ fail loudly). */
|
|
230
|
+
export class WorkerJudgmentOutboxCorruptError extends WorkerJudgmentEmitterError {
|
|
231
|
+
constructor(path, detail) {
|
|
232
|
+
super('worker_judgment_outbox_corrupt', `Stored outbox ${path} ${detail}`);
|
|
233
|
+
this.name = 'WorkerJudgmentOutboxCorruptError';
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/** Recompute the receipt_digest from the receipt body so a tampered or truncated body cannot ride on a stale digest string. */
|
|
237
|
+
function recomputeReceiptDigest(receipt) {
|
|
238
|
+
const core = { ...receipt };
|
|
239
|
+
delete core.receipt_digest;
|
|
240
|
+
return sha256Hex(canonicalJson(core));
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Read the digest and the recorded delivery state of a receipt already on disk.
|
|
244
|
+
* A re-emit must compare the digest (§6 conflict) and must not undo delivery
|
|
245
|
+
* progress, so the stored status is read too. The stored digest string is not
|
|
246
|
+
* trusted on its own: the receipt_digest is recomputed from the receipt body,
|
|
247
|
+
* the outbox schema and the delivery status are verified, and any mismatch is a
|
|
248
|
+
* loud `WorkerJudgmentOutboxCorruptError` rather than a silent re-send or
|
|
249
|
+
* overwrite. Returns `null` only when the file is genuinely absent.
|
|
250
|
+
*/
|
|
251
|
+
function readStoredOutboxState(path) {
|
|
252
|
+
let raw;
|
|
253
|
+
try {
|
|
254
|
+
raw = readFileSync(path, 'utf8');
|
|
255
|
+
}
|
|
256
|
+
catch (error) {
|
|
257
|
+
if (isErrno(error, 'ENOENT'))
|
|
258
|
+
return null;
|
|
259
|
+
throw new WorkerJudgmentOutboxCorruptError(path, 'could not be read');
|
|
260
|
+
}
|
|
261
|
+
let parsed;
|
|
262
|
+
try {
|
|
263
|
+
parsed = JSON.parse(raw);
|
|
264
|
+
}
|
|
265
|
+
catch {
|
|
266
|
+
throw new WorkerJudgmentOutboxCorruptError(path, 'is not valid JSON');
|
|
267
|
+
}
|
|
268
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
269
|
+
throw new WorkerJudgmentOutboxCorruptError(path, 'is not an object');
|
|
270
|
+
}
|
|
271
|
+
if (parsed.schema_version !== WORKER_JUDGMENT_OUTBOX_SCHEMA) {
|
|
272
|
+
throw new WorkerJudgmentOutboxCorruptError(path, 'has an unexpected schema_version');
|
|
273
|
+
}
|
|
274
|
+
const receipt = parsed.receipt;
|
|
275
|
+
if (!receipt || typeof receipt !== 'object' || Array.isArray(receipt)) {
|
|
276
|
+
throw new WorkerJudgmentOutboxCorruptError(path, 'is missing its receipt');
|
|
277
|
+
}
|
|
278
|
+
const digest = receipt.receipt_digest;
|
|
279
|
+
if (typeof digest !== 'string' || !digest) {
|
|
280
|
+
throw new WorkerJudgmentOutboxCorruptError(path, 'is missing its receipt_digest');
|
|
281
|
+
}
|
|
282
|
+
let recomputed;
|
|
283
|
+
try {
|
|
284
|
+
recomputed = recomputeReceiptDigest(receipt);
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
throw new WorkerJudgmentOutboxCorruptError(path, 'has a receipt body that cannot be canonicalized');
|
|
288
|
+
}
|
|
289
|
+
if (recomputed !== digest) {
|
|
290
|
+
throw new WorkerJudgmentOutboxCorruptError(path, 'has a receipt_digest that does not match its body');
|
|
291
|
+
}
|
|
292
|
+
const delivery = parsed.delivery;
|
|
293
|
+
if (!delivery || typeof delivery !== 'object' || Array.isArray(delivery)) {
|
|
294
|
+
throw new WorkerJudgmentOutboxCorruptError(path, 'is missing its delivery state');
|
|
295
|
+
}
|
|
296
|
+
const rawStatus = delivery.status;
|
|
297
|
+
if (!DELIVERY_STATUSES.includes(rawStatus)) {
|
|
298
|
+
throw new WorkerJudgmentOutboxCorruptError(path, 'has an invalid delivery status');
|
|
299
|
+
}
|
|
300
|
+
const status = rawStatus;
|
|
301
|
+
const rawError = delivery.last_error_code;
|
|
302
|
+
if (rawError !== undefined && typeof rawError !== 'string') {
|
|
303
|
+
throw new WorkerJudgmentOutboxCorruptError(path, 'has an invalid last_error_code');
|
|
304
|
+
}
|
|
305
|
+
return { receipt_digest: digest, status, ...(typeof rawError === 'string' ? { last_error_code: rawError } : {}) };
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Record a successful delivery as a separate marker file created exclusively
|
|
309
|
+
* (`wx`). The outbox body is never rewritten on success, so a slow concurrent
|
|
310
|
+
* failure cannot clobber a recorded success: the marker's presence — not a body
|
|
311
|
+
* status — is the authoritative "delivered" signal, and a marker, once created,
|
|
312
|
+
* is never removed. Creating a marker that already exists is treated as success:
|
|
313
|
+
* another writer, or an earlier crash, already delivered it. The marker carries
|
|
314
|
+
* no judgment body, only a schema tag and the time it was recorded, and its
|
|
315
|
+
* content is never read: presence alone means saved, so a crash between creating
|
|
316
|
+
* and writing the marker still reads as delivered.
|
|
317
|
+
*/
|
|
318
|
+
function recordDeliverySuccess(markerPath, now) {
|
|
319
|
+
let fd;
|
|
320
|
+
try {
|
|
321
|
+
fd = openSync(markerPath, 'wx', 0o600);
|
|
322
|
+
}
|
|
323
|
+
catch (error) {
|
|
324
|
+
if (isErrno(error, 'EEXIST'))
|
|
325
|
+
return;
|
|
326
|
+
throw error;
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
writeFileSync(fd, `${JSON.stringify({ schema_version: WORKER_JUDGMENT_SENT_SCHEMA, recorded_at: now().toISOString() })}\n`);
|
|
330
|
+
}
|
|
331
|
+
finally {
|
|
332
|
+
closeSync(fd);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
/** True when a success marker is present. Presence is the only signal; the content is never read. */
|
|
336
|
+
function deliverySucceeded(markerPath) {
|
|
337
|
+
return existsSync(markerPath);
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Turn a Worker turn into a receipt and write it to the local outbox, then —
|
|
341
|
+
* only if a transport is injected — attempt a single delivery and record its
|
|
342
|
+
* status. With no transport the receipt stays `pending` locally. Re-emitting
|
|
343
|
+
* the identical turn is idempotent; a different receipt under the same
|
|
344
|
+
* resolution id is a loud conflict. Nothing here writes the raw session/turn
|
|
345
|
+
* ids, the prompt, the response, or any credential.
|
|
346
|
+
*/
|
|
347
|
+
export async function emitWorkerJudgment(input, options) {
|
|
348
|
+
if (!options.journalRoot)
|
|
349
|
+
throw new WorkerJudgmentEmitterError('worker_judgment_journal_root_required', 'journalRoot is required');
|
|
350
|
+
const now = options.now ?? (() => new Date());
|
|
351
|
+
const built = buildWorkerJudgmentReceipt(input, {
|
|
352
|
+
effectiveAfter: options.effectiveAfter,
|
|
353
|
+
now,
|
|
354
|
+
maxFutureSkewMs: options.maxFutureSkewMs
|
|
355
|
+
});
|
|
356
|
+
const dir = resolveWorkerJudgmentTurnDir(options.journalRoot, input.session_id, input.turn_id);
|
|
357
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
358
|
+
if (built.outcome === 'skipped') {
|
|
359
|
+
const target = join(dir, 'skip.json');
|
|
360
|
+
atomicWriteReplace(target, {
|
|
361
|
+
schema_version: WORKER_JUDGMENT_SKIP_SCHEMA,
|
|
362
|
+
entrypoint: input.entrypoint,
|
|
363
|
+
turn_ref: `${sha256Hex(input.session_id)}/${sha256Hex(input.turn_id)}`,
|
|
364
|
+
reason_code: built.reason_code,
|
|
365
|
+
recorded_at: now().toISOString()
|
|
366
|
+
}, now);
|
|
367
|
+
return { outcome: 'skipped', reason_code: built.reason_code, path: target };
|
|
368
|
+
}
|
|
369
|
+
const receipt = built.receipt;
|
|
370
|
+
const target = join(dir, `${receipt.resolution_id}.json`);
|
|
371
|
+
const markerPath = `${target}.sent`;
|
|
372
|
+
let deduped = false;
|
|
373
|
+
let stored = null;
|
|
374
|
+
try {
|
|
375
|
+
atomicPublishNoReplace(target, {
|
|
376
|
+
schema_version: WORKER_JUDGMENT_OUTBOX_SCHEMA,
|
|
377
|
+
receipt,
|
|
378
|
+
delivery: { status: 'pending', attempt: 1, queued_at: now().toISOString() }
|
|
379
|
+
}, now);
|
|
380
|
+
}
|
|
381
|
+
catch (error) {
|
|
382
|
+
if (!isErrno(error, 'EEXIST'))
|
|
383
|
+
throw error;
|
|
384
|
+
stored = readStoredOutboxState(target);
|
|
385
|
+
if (!stored || stored.receipt_digest !== receipt.receipt_digest)
|
|
386
|
+
throw new WorkerJudgmentConflictError(receipt.resolution_id);
|
|
387
|
+
deduped = true;
|
|
388
|
+
}
|
|
389
|
+
// A delivered receipt is marked by a `.sent` file, never by the outbox body:
|
|
390
|
+
// if the marker is present the receipt was already saved and must not be
|
|
391
|
+
// re-sent or downgraded, whatever the body or a later transport says.
|
|
392
|
+
if (deliverySucceeded(markerPath)) {
|
|
393
|
+
return { outcome: 'emitted', status: 'saved', receipt, path: target, deduped };
|
|
394
|
+
}
|
|
395
|
+
// Legacy success: an outbox written before the `.sent` marker existed recorded
|
|
396
|
+
// delivery only in its body. A marker-less `saved` / `already_saved` body is
|
|
397
|
+
// still an authoritative success, so honor it exactly like a marker — never
|
|
398
|
+
// re-send through the transport, and never let a later failure downgrade it.
|
|
399
|
+
if (stored && isSuccessStatus(stored.status)) {
|
|
400
|
+
return {
|
|
401
|
+
outcome: 'emitted',
|
|
402
|
+
status: stored.status,
|
|
403
|
+
receipt,
|
|
404
|
+
path: target,
|
|
405
|
+
deduped,
|
|
406
|
+
...(stored.last_error_code ? { last_error_code: stored.last_error_code } : {})
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
if (!options.transport) {
|
|
410
|
+
// No transport: the receipt keeps whatever the body already recorded
|
|
411
|
+
// (`pending` on a first write, or a prior `failed`), never a fresh success.
|
|
412
|
+
const status = stored ? stored.status : 'pending';
|
|
413
|
+
return {
|
|
414
|
+
outcome: 'emitted',
|
|
415
|
+
status,
|
|
416
|
+
receipt,
|
|
417
|
+
path: target,
|
|
418
|
+
deduped,
|
|
419
|
+
...(stored?.last_error_code ? { last_error_code: stored.last_error_code } : {})
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
let status = 'pending';
|
|
423
|
+
let lastErrorCode;
|
|
424
|
+
try {
|
|
425
|
+
const result = await options.transport.send(receipt);
|
|
426
|
+
status = result.status;
|
|
427
|
+
if (result.status === 'blocked_credential' || result.status === 'failed')
|
|
428
|
+
lastErrorCode = result.reason_code;
|
|
429
|
+
}
|
|
430
|
+
catch (error) {
|
|
431
|
+
status = 'failed';
|
|
432
|
+
lastErrorCode = error instanceof WorkerJudgmentEmitterError ? error.code : 'worker_judgment_transport_error';
|
|
433
|
+
}
|
|
434
|
+
if (isSuccessStatus(status)) {
|
|
435
|
+
// Success is recorded only by exclusively creating the marker; the body is
|
|
436
|
+
// left as published. An already-present marker means a concurrent writer (or
|
|
437
|
+
// an earlier crash mid-delivery) already recorded success, which is fine.
|
|
438
|
+
recordDeliverySuccess(markerPath, now);
|
|
439
|
+
return { outcome: 'emitted', status, receipt, path: target, deduped };
|
|
440
|
+
}
|
|
441
|
+
// Delivery failed. If a concurrent re-emit already recorded success, keep that
|
|
442
|
+
// success and neither record the failure in the body nor touch the marker.
|
|
443
|
+
if (deliverySucceeded(markerPath)) {
|
|
444
|
+
return { outcome: 'emitted', status: 'saved', receipt, path: target, deduped };
|
|
445
|
+
}
|
|
446
|
+
atomicWriteReplace(target, {
|
|
447
|
+
schema_version: WORKER_JUDGMENT_OUTBOX_SCHEMA,
|
|
448
|
+
receipt,
|
|
449
|
+
delivery: {
|
|
450
|
+
status,
|
|
451
|
+
attempt: 1,
|
|
452
|
+
queued_at: now().toISOString(),
|
|
453
|
+
...(lastErrorCode ? { last_error_code: lastErrorCode } : {})
|
|
454
|
+
}
|
|
455
|
+
}, now);
|
|
456
|
+
return { outcome: 'emitted', status, receipt, path: target, deduped, ...(lastErrorCode ? { last_error_code: lastErrorCode } : {}) };
|
|
457
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unson/brainbase-mcp",
|
|
3
|
-
"version": "0.48.
|
|
3
|
+
"version": "0.48.4",
|
|
4
4
|
"description": "Local-first Brainbase judgment OS that lets supported AI agents reuse a user's approved goals, priorities, decisions, and judgment criteria.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -624,5 +624,5 @@
|
|
|
624
624
|
"url": "https://github.com/Unson-LLC/brainbase/issues"
|
|
625
625
|
},
|
|
626
626
|
"homepage": "https://github.com/Unson-LLC/brainbase#readme",
|
|
627
|
-
"gitHead": "
|
|
627
|
+
"gitHead": "28e45e4b142af07f8ece86fc4068e2121ebe4bbc"
|
|
628
628
|
}
|
package/ui/brainbase-tokens.css
CHANGED
|
@@ -11,6 +11,14 @@
|
|
|
11
11
|
* Status colors retain their semantic meaning; hosts can still override tokens.
|
|
12
12
|
*/
|
|
13
13
|
:root {
|
|
14
|
+
/* Shared motion curves and dismissal durations. */
|
|
15
|
+
--bb-ease-out: cubic-bezier(0.23, 1, 0.32, 1);
|
|
16
|
+
--bb-ease-in-out: cubic-bezier(0.77, 0, 0.175, 1); /* On-screen movement/position swaps only, not enter/exit. */
|
|
17
|
+
--bb-ease-drawer: cubic-bezier(0.32, 0.72, 0, 1);
|
|
18
|
+
--bb-ease-drawer-in: ease-out;
|
|
19
|
+
--bb-duration-drawer-in: 180ms;
|
|
20
|
+
--bb-duration-drawer-out: 150ms;
|
|
21
|
+
--bb-duration-toast-out: 200ms;
|
|
14
22
|
--bb-color-ink: #202939;
|
|
15
23
|
--bb-color-muted: #6b7280;
|
|
16
24
|
/* Small secondary text on tinted surfaces needs a slightly darker mix. */
|
|
@@ -111,6 +119,8 @@
|
|
|
111
119
|
--bb-tab-line-height: 20px;
|
|
112
120
|
--bb-tab-font-weight: 500;
|
|
113
121
|
--bb-tab-indicator-size: 2px;
|
|
122
|
+
--bb-tab-indicator-duration: 260ms;
|
|
123
|
+
--bb-tab-indicator-ease: cubic-bezier(.2, .8, .2, 1);
|
|
114
124
|
--bb-tab-count-size: 20px;
|
|
115
125
|
--bb-tab-count-font-size: 12px;
|
|
116
126
|
/* Opt-in search band: dimensions and interaction surfaces. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { workspaceTabStrip } from './workspace-kit.js';
|
|
2
2
|
/*
|
|
3
3
|
* 「情報と関係」: what the local Graph holds, how records are connected, and
|
|
4
4
|
* where to correct a mistake so the next MCP use sees the fix.
|
|
@@ -469,7 +469,7 @@ export function createGraphRegistryView({
|
|
|
469
469
|
.map(({ id }) => id)
|
|
470
470
|
.filter((id) => id === selected || counts.get(id)?.count !== 0);
|
|
471
471
|
const tabs = makeElement(doc, 'div', { className: 'bb-gr-tabs', attrs: { role: 'tablist', 'aria-label': '種類' } });
|
|
472
|
-
|
|
472
|
+
workspaceTabStrip(tabs, { memoryKey: 'graph-registry-kinds' });
|
|
473
473
|
for (const id of ['', ...ids]) {
|
|
474
474
|
const item = counts.get(id);
|
|
475
475
|
const count = Number.isInteger(item?.count) ? String(item.count)
|
package/ui/inbox.css
CHANGED
|
@@ -154,7 +154,7 @@ a.bb-inbox-title:focus-visible {
|
|
|
154
154
|
border-radius: 999px;
|
|
155
155
|
padding: 0 8px;
|
|
156
156
|
background: var(--bb-color-danger-soft);
|
|
157
|
-
color: var(--bb-color-
|
|
157
|
+
color: var(--bb-color-inline-error);
|
|
158
158
|
font-weight: var(--bb-font-weight-medium);
|
|
159
159
|
}
|
|
160
160
|
|
package/ui/inbox.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { workspaceTabStrip } from './workspace-kit.js';
|
|
2
2
|
/*
|
|
3
3
|
* 受信箱 (story-inbox-stage1-v1, docs/specs/inbox-stage1.md).
|
|
4
4
|
*
|
|
@@ -647,7 +647,7 @@ export function createInboxUI({
|
|
|
647
647
|
|
|
648
648
|
function renderTabs(waitingCount) {
|
|
649
649
|
const bar = el(doc, 'div', { className: 'bb-inbox-tabs', attrs: { role: 'tablist', 'aria-label': '受信箱' } });
|
|
650
|
-
|
|
650
|
+
workspaceTabStrip(bar, { memoryKey: 'inbox-tabs' });
|
|
651
651
|
for (const [id, label] of [['waiting', '対応待ち'], ['notices', 'お知らせ']]) {
|
|
652
652
|
const selected = state.route.tab === id;
|
|
653
653
|
const tab = el(doc, 'button', {
|
|
@@ -898,7 +898,7 @@ export function createInboxUI({
|
|
|
898
898
|
if (!notices || notices.phase === 'not_collected') {
|
|
899
899
|
view.append(el(doc, 'p', { className: 'bb-inbox-uncollected', text: 'お知らせはまだ集めていません。AIに任せた仕事の終わり・議事録ができたこと・申請の結果は、これから集めます。' }));
|
|
900
900
|
} else if (notices.phase === 'unavailable') {
|
|
901
|
-
view.append(workspaceErrorCard(doc, { title: 'お知らせを読めませんでした', message: `理由: ${reasonText(notices.reason)}。0
|
|
901
|
+
view.append(workspaceErrorCard(doc, { title: 'お知らせを読めませんでした', message: `理由: ${reasonText(notices.reason)}。0件ではありません。`, open: true }));
|
|
902
902
|
} else if (notices.items.length === 0) {
|
|
903
903
|
view.append(el(doc, 'p', { className: 'bb-inbox-empty', text: 'お知らせはありません。' }));
|
|
904
904
|
}
|
|
@@ -947,7 +947,7 @@ export function createInboxUI({
|
|
|
947
947
|
if (!isToday && state.route.tab === 'notices') {
|
|
948
948
|
view.append(renderNotices());
|
|
949
949
|
} else if (state.phase === 'error' && !shown) {
|
|
950
|
-
view.append(workspaceErrorCard(doc, { title: '受信箱を読めませんでした', message: `理由: ${reasonText(state.reason)}。0件ではありません。`, onRetry: () => void load() }));
|
|
950
|
+
view.append(workspaceErrorCard(doc, { title: '受信箱を読めませんでした', message: `理由: ${reasonText(state.reason)}。0件ではありません。`, onRetry: () => void load(), open: true }));
|
|
951
951
|
} else if (shown) {
|
|
952
952
|
if (isToday) view.append(state.route.view === 'waiting' ? renderTodayWaiting(shown) : renderSet(shown, state.route.view));
|
|
953
953
|
else view.append(state.route.view === 'waiting' ? renderWaiting(shown) : renderSet(shown, state.route.view));
|
package/ui/local-web-shell.css
CHANGED
|
@@ -272,17 +272,6 @@
|
|
|
272
272
|
gap: 8px;
|
|
273
273
|
}
|
|
274
274
|
|
|
275
|
-
.bb-pc-action-row .bb-ws-button.is-primary {
|
|
276
|
-
border-color: var(--bb-color-action);
|
|
277
|
-
background: var(--bb-color-action);
|
|
278
|
-
color: var(--bb-color-action-text);
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
.bb-pc-action-row .bb-ws-button.is-primary:hover:not(:disabled) {
|
|
282
|
-
border-color: var(--bb-color-action-hover);
|
|
283
|
-
background: var(--bb-color-action-hover);
|
|
284
|
-
}
|
|
285
|
-
|
|
286
275
|
.bb-pc-action-row .bb-ws-button[data-adds]::before {
|
|
287
276
|
content: '+';
|
|
288
277
|
}
|
package/ui/project-workspace.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { workspaceTabStrip } from './workspace-kit.js';
|
|
2
2
|
/*
|
|
3
3
|
* Shared project knowledge workspace.
|
|
4
4
|
*
|
|
@@ -1254,7 +1254,7 @@ export function createProjectKnowledgeWorkspace({
|
|
|
1254
1254
|
});
|
|
1255
1255
|
const body = makeElement(doc, 'div', { className: 'bb-pkw-body' });
|
|
1256
1256
|
const tabs = makeElement(doc, 'div', { className: 'bb-pkw-tabs', attrs: { role: 'tablist', 'aria-label': 'プロジェクト情報の表示' } });
|
|
1257
|
-
|
|
1257
|
+
const tabStrip = workspaceTabStrip(tabs);
|
|
1258
1258
|
const panels = makeElement(doc, 'div', { className: 'bb-pkw-panels' });
|
|
1259
1259
|
root.append(makeElement(doc, 'div', { className: 'bb-pkw-kicker', text: 'プロジェクトの記録' }));
|
|
1260
1260
|
const header = makeElement(doc, 'header', { className: 'bb-pkw-header' });
|
|
@@ -1562,6 +1562,7 @@ export function createProjectKnowledgeWorkspace({
|
|
|
1562
1562
|
if (typeof onTabChange === 'function') onTabChange(activeTab);
|
|
1563
1563
|
teardownGraph();
|
|
1564
1564
|
tabs.replaceChildren(tabButton('概要', 'overview'), tabButton('情報を探す', 'graph'));
|
|
1565
|
+
tabStrip.update();
|
|
1565
1566
|
panels.replaceChildren();
|
|
1566
1567
|
const actions = { openOverview, openWorkList, openWorkDetail, openRecordDetail, openSectionList, openGraphEntity: selectAndExplore,
|
|
1567
1568
|
retryParticipants: typeof onRetryProject === 'function' ? () => onRetryProject(workspaceProjectId) : null,
|
package/ui/workspace-kit.css
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
|
|
14
14
|
.bb-ws-breadcrumb {
|
|
15
15
|
margin-bottom: 24px;
|
|
16
|
-
color: var(--bb-color-
|
|
16
|
+
color: var(--bb-color-muted);
|
|
17
17
|
font-size: 11px;
|
|
18
18
|
letter-spacing: .02em;
|
|
19
19
|
}
|
|
@@ -165,7 +165,7 @@
|
|
|
165
165
|
color: var(--bb-color-action-text);
|
|
166
166
|
}
|
|
167
167
|
|
|
168
|
-
.bb-ws-button.is-primary:hover {
|
|
168
|
+
.bb-ws-button.is-primary:hover:not(:disabled) {
|
|
169
169
|
border-color: var(--bb-color-action-hover);
|
|
170
170
|
background: var(--bb-color-action-hover);
|
|
171
171
|
}
|
|
@@ -573,10 +573,10 @@
|
|
|
573
573
|
margin: 0 0 0 auto; padding: 0; border: 0; border-left: 1px solid var(--bb-color-border);
|
|
574
574
|
border-radius: 0; background: var(--bb-color-panel); color: var(--bb-color-ink); box-shadow: var(--bb-shadow-drawer); overflow: auto;
|
|
575
575
|
}
|
|
576
|
-
.bb-ws-drawer[open] { animation: bb-ws-drawer-in 180ms ease-out; }
|
|
576
|
+
.bb-ws-drawer[open] { animation: bb-ws-drawer-in var(--bb-duration-drawer-in, 180ms) var(--bb-ease-drawer-in, ease-out); }
|
|
577
577
|
.bb-ws-drawer::backdrop { background: var(--bb-color-drawer-overlay); }
|
|
578
|
-
.bb-ws-drawer.is-closing { animation: bb-ws-drawer-out
|
|
579
|
-
.bb-ws-drawer.is-closing::backdrop { animation: bb-ws-drawer-backdrop-out
|
|
578
|
+
.bb-ws-drawer.is-closing { animation: bb-ws-drawer-out var(--bb-duration-drawer-out, 150ms) var(--bb-ease-drawer, cubic-bezier(0.32, 0.72, 0, 1)) both; pointer-events: none; }
|
|
579
|
+
.bb-ws-drawer.is-closing::backdrop { animation: bb-ws-drawer-backdrop-out var(--bb-duration-drawer-out, 150ms) var(--bb-ease-drawer, cubic-bezier(0.32, 0.72, 0, 1)) both; }
|
|
580
580
|
.bb-ws-drawer .bb-ws-dialog-head { align-items: center; padding: 14px 16px 14px 28px; }
|
|
581
581
|
.bb-ws-drawer .bb-ws-dialog-head h2 { font-weight: var(--bb-font-weight-medium); line-height: 1.35; }
|
|
582
582
|
.bb-ws-drawer .bb-ws-dialog-body { padding: 18px 28px 32px; }
|
|
@@ -620,7 +620,7 @@
|
|
|
620
620
|
}
|
|
621
621
|
.bb-ws-loading-stage-title { margin: 0; font-weight: var(--bb-font-weight-medium); }
|
|
622
622
|
.bb-ws-loading-stage-detail { margin: 0; color: var(--bb-color-muted, inherit); font-size: .875rem; }
|
|
623
|
-
.bb-ws-error-card.is-dismissing { animation: bb-ws-notification-out
|
|
623
|
+
.bb-ws-error-card.is-dismissing { animation: bb-ws-notification-out var(--bb-duration-toast-out, 200ms) var(--bb-ease-out, cubic-bezier(0.23, 1, 0.32, 1)) both; pointer-events: none; }
|
|
624
624
|
@keyframes bb-ws-notification-out { to { opacity: 0; transform: translateX(28px); } }
|
|
625
625
|
@media (max-width:760px) { .bb-ws-drawer { width: 100vw; border-left: 0; } }
|
|
626
626
|
@media (prefers-reduced-motion:reduce) {
|
|
@@ -840,6 +840,26 @@
|
|
|
840
840
|
line-height: var(--bb-tab-count-size);
|
|
841
841
|
font-weight: var(--bb-tab-font-weight);
|
|
842
842
|
}
|
|
843
|
+
/* workspaceTabStrip: one bar slides between tabs once the selected tab was measured. */
|
|
844
|
+
.bb-ws-tabs.is-indicator-ready { position: relative; }
|
|
845
|
+
.bb-ws-tabs.is-indicator-ready > :is([role="tab"], a, button):is([aria-selected="true"], [aria-current="page"], [aria-pressed="true"]),
|
|
846
|
+
.bb-ws-tabs.is-indicator-ready > :is([role="tab"], a, button):is([aria-selected="true"], [aria-current="page"], [aria-pressed="true"]):hover {
|
|
847
|
+
box-shadow: none;
|
|
848
|
+
}
|
|
849
|
+
.bb-ws-tabs.is-indicator-ready::after {
|
|
850
|
+
content: "";
|
|
851
|
+
position: absolute;
|
|
852
|
+
left: 0;
|
|
853
|
+
bottom: 0;
|
|
854
|
+
width: var(--bb-tab-indicator-width, 0px);
|
|
855
|
+
height: var(--bb-tab-indicator-size);
|
|
856
|
+
background: var(--bb-color-ink);
|
|
857
|
+
transform: translateX(var(--bb-tab-indicator-x, 0px));
|
|
858
|
+
transition: transform var(--bb-tab-indicator-duration) var(--bb-tab-indicator-ease), width var(--bb-tab-indicator-duration) var(--bb-tab-indicator-ease);
|
|
859
|
+
pointer-events: none;
|
|
860
|
+
}
|
|
861
|
+
.bb-ws-tabs.is-indicator-instant::after { transition: none; }
|
|
862
|
+
@media (prefers-reduced-motion: reduce) { .bb-ws-tabs.is-indicator-ready::after { transition: none; } }
|
|
843
863
|
.bb-ws-tabs::-webkit-scrollbar { display: none; }
|
|
844
864
|
.bb-ws-tabs[hidden],
|
|
845
865
|
.bb-ws-tabs > [hidden] { display: none; }
|
package/ui/workspace-kit.js
CHANGED
|
@@ -328,6 +328,14 @@ export function workspaceHelp(doc, { text, label } = {}) {
|
|
|
328
328
|
const drawerClosings = new WeakMap();
|
|
329
329
|
const notificationClosings = new WeakMap();
|
|
330
330
|
const reducedMotion = node => node.ownerDocument?.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true;
|
|
331
|
+
const animationFallback = (node, margin, fallback) => {
|
|
332
|
+
const durations = node.ownerDocument?.defaultView?.getComputedStyle?.(node).animationDuration;
|
|
333
|
+
const duration = Math.max(...(durations ?? '').split(',').map(value => {
|
|
334
|
+
const match = value.trim().match(/^(\d*\.?\d+)(ms|s)$/);
|
|
335
|
+
return match ? Number(match[1]) * (match[2] === 's' ? 1000 : 1) : NaN;
|
|
336
|
+
}));
|
|
337
|
+
return Number.isFinite(duration) && duration > 0 ? duration + margin : fallback;
|
|
338
|
+
};
|
|
331
339
|
|
|
332
340
|
/** Apply the same native-dialog presentation to host-owned and kit drawers. */
|
|
333
341
|
export function workspaceApplyDrawer(dialog) {
|
|
@@ -358,7 +366,7 @@ export function workspaceCloseDrawer(dialog, finish) {
|
|
|
358
366
|
dialog.addEventListener('animationend', ended);
|
|
359
367
|
dialog.addEventListener('close', cancel);
|
|
360
368
|
dialog.classList.add('is-closing');
|
|
361
|
-
timer = setTimeout(complete,
|
|
369
|
+
timer = setTimeout(complete, animationFallback(dialog, 70, 220)); // Animation cancellation / background-tab fallback.
|
|
362
370
|
return cancel;
|
|
363
371
|
}
|
|
364
372
|
|
|
@@ -496,14 +504,14 @@ export function workspaceDismissNotification(card, onDismiss) {
|
|
|
496
504
|
const complete = () => { if (!active) return; cancel(); remove(); onDismiss?.(); };
|
|
497
505
|
const ended = event => { if (event.target === card && event.animationName === 'bb-ws-notification-out') complete(); };
|
|
498
506
|
notificationClosings.set(card, cancel); card.addEventListener('animationend', ended);
|
|
499
|
-
card.classList.add('is-dismissing'); timer = setTimeout(complete,
|
|
507
|
+
card.classList.add('is-dismissing'); timer = setTimeout(complete, animationFallback(card, 50, 250));
|
|
500
508
|
return cancel;
|
|
501
509
|
}
|
|
502
510
|
|
|
503
|
-
/** Persistent,
|
|
504
|
-
export function workspaceErrorCard(doc, { title, message, tone = 'danger', onRetry } = {}) {
|
|
511
|
+
/** Persistent notification, closed unless `open`. The caller owns its lifecycle. */
|
|
512
|
+
export function workspaceErrorCard(doc, { title, message, tone = 'danger', onRetry, open = false } = {}) {
|
|
505
513
|
const card = workspaceNotificationCard(doc, { tone, className: 'bb-ws-error-card', role: 'listitem' });
|
|
506
|
-
const details = el(doc, 'details');
|
|
514
|
+
const details = el(doc, 'details'); details.open = open;
|
|
507
515
|
const summary = el(doc, 'summary', { attrs: { 'aria-label': `${title}の通知` } });
|
|
508
516
|
summary.append(el(doc, 'span', { className: 'bb-ws-error-symbol', text: '!', attrs: { 'aria-hidden': 'true' } }), el(doc, 'span', { text: title }));
|
|
509
517
|
details.append(summary, el(doc, 'p', { text: message })); card.append(details);
|
|
@@ -783,6 +791,112 @@ export function workspaceTabList(root) {
|
|
|
783
791
|
return root;
|
|
784
792
|
}
|
|
785
793
|
|
|
794
|
+
const TAB_STRIP_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'Home', 'End']);
|
|
795
|
+
// How long a key move may wait for the host to redraw before focus is no longer brought back.
|
|
796
|
+
const TAB_STRIP_FOCUS_WINDOW_MS = 5000;
|
|
797
|
+
const tabStrips = new WeakMap();
|
|
798
|
+
const tabStripMemory = new Map();
|
|
799
|
+
const isEnabledTab = node => node?.getAttribute?.('role') === 'tab' && !node.hidden && !node.disabled && node.getAttribute('aria-disabled') !== 'true';
|
|
800
|
+
const isSelectedTab = node => node?.getAttribute?.('aria-selected') === 'true' || node?.getAttribute?.('aria-current') === 'page' || node?.getAttribute?.('aria-pressed') === 'true';
|
|
801
|
+
|
|
802
|
+
/** Opt-in keyboard switching and a sliding indicator on top of `workspaceTabList`.
|
|
803
|
+
* Selection stays with the host: a key move calls the tab's own click(). Hosts
|
|
804
|
+
* that redraw the strip as new nodes pass the same `memoryKey`; hosts that keep
|
|
805
|
+
* the root and replace its children call `update()` after drawing.
|
|
806
|
+
*/
|
|
807
|
+
export function workspaceTabStrip(root, { memoryKey } = {}) {
|
|
808
|
+
workspaceTabList(root);
|
|
809
|
+
if (tabStrips.has(root)) return tabStrips.get(root);
|
|
810
|
+
const doc = root.ownerDocument;
|
|
811
|
+
const view = doc?.defaultView;
|
|
812
|
+
const schedule = typeof view?.requestAnimationFrame === 'function' ? fn => view.requestAnimationFrame(fn) : fn => { Promise.resolve().then(fn); };
|
|
813
|
+
const key = typeof memoryKey === 'string' && memoryKey ? memoryKey : null;
|
|
814
|
+
if (key && !tabStripMemory.has(key)) tabStripMemory.set(key, { x: null, width: null, focusUntil: 0 });
|
|
815
|
+
const local = { x: null, width: null, focusUntil: 0 };
|
|
816
|
+
const memory = () => (key ? tabStripMemory.get(key) : local);
|
|
817
|
+
const children = () => Array.from(root.children ?? []);
|
|
818
|
+
const tabs = () => children().filter(isEnabledTab);
|
|
819
|
+
const selectedTab = () => children().find(isSelectedTab) ?? null;
|
|
820
|
+
let placed = false;
|
|
821
|
+
let destroyed = false;
|
|
822
|
+
|
|
823
|
+
const setIndicator = ({ x, width }) => {
|
|
824
|
+
root.style.setProperty('--bb-tab-indicator-x', `${x}px`);
|
|
825
|
+
root.style.setProperty('--bb-tab-indicator-width', `${width}px`);
|
|
826
|
+
};
|
|
827
|
+
const placeIndicator = tab => {
|
|
828
|
+
const width = tab?.offsetWidth;
|
|
829
|
+
if (!(width > 0) || typeof root.style?.setProperty !== 'function') {
|
|
830
|
+
toggleWorkspaceClass(root, 'is-indicator-ready', false); placed = false; return;
|
|
831
|
+
}
|
|
832
|
+
// Measure from the strip itself: before the strip is positioned, offsetLeft counts from an outer box.
|
|
833
|
+
const box = tab.getBoundingClientRect?.();
|
|
834
|
+
const origin = root.getBoundingClientRect?.();
|
|
835
|
+
const target = box && origin ? { x: box.left - origin.left + (root.scrollLeft || 0), width: box.width } : { x: tab.offsetLeft, width };
|
|
836
|
+
const mem = memory();
|
|
837
|
+
if (!placed) {
|
|
838
|
+
// A new strip starts where the last strip with the same key left the bar, then slides.
|
|
839
|
+
const from = mem.width > 0 && !reducedMotion(root) ? mem : target;
|
|
840
|
+
toggleWorkspaceClass(root, 'is-indicator-instant', true);
|
|
841
|
+
setIndicator(from); toggleWorkspaceClass(root, 'is-indicator-ready', true);
|
|
842
|
+
void root.offsetWidth;
|
|
843
|
+
toggleWorkspaceClass(root, 'is-indicator-instant', false);
|
|
844
|
+
}
|
|
845
|
+
setIndicator(target); placed = true;
|
|
846
|
+
mem.x = target.x; mem.width = target.width;
|
|
847
|
+
};
|
|
848
|
+
const restoreFocus = () => {
|
|
849
|
+
const mem = memory();
|
|
850
|
+
if (!(mem.focusUntil > Date.now())) return;
|
|
851
|
+
const target = selectedTab();
|
|
852
|
+
if (!target || root.isConnected === false) return;
|
|
853
|
+
const active = doc?.activeElement ?? null;
|
|
854
|
+
if (active === target) { mem.focusUntil = 0; return; }
|
|
855
|
+
const lost = !active || active === doc.body || active.isConnected === false;
|
|
856
|
+
// Focus moved somewhere else: the viewer chose it, so leave it there.
|
|
857
|
+
if (!lost && !root.contains?.(active)) { mem.focusUntil = 0; return; }
|
|
858
|
+
// Still on a tab of this strip: the host has not finished selecting yet.
|
|
859
|
+
if (!lost) return;
|
|
860
|
+
target.focus?.({ preventScroll: true });
|
|
861
|
+
target.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
|
|
862
|
+
mem.focusUntil = 0;
|
|
863
|
+
};
|
|
864
|
+
const update = () => {
|
|
865
|
+
// A strip the host already replaced must not move the shared memory back.
|
|
866
|
+
if (destroyed || root.isConnected === false) return;
|
|
867
|
+
const all = tabs();
|
|
868
|
+
const selected = selectedTab();
|
|
869
|
+
const focusable = all.includes(selected) ? selected : all[0];
|
|
870
|
+
for (const tab of all) tab.setAttribute('tabindex', tab === focusable ? '0' : '-1');
|
|
871
|
+
placeIndicator(selected);
|
|
872
|
+
restoreFocus();
|
|
873
|
+
};
|
|
874
|
+
const keydown = event => {
|
|
875
|
+
if (!TAB_STRIP_KEYS.has(event.key) || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
|
|
876
|
+
const all = tabs();
|
|
877
|
+
const current = all.indexOf(event.target);
|
|
878
|
+
if (current < 0 || all.length < 2) return;
|
|
879
|
+
event.preventDefault?.();
|
|
880
|
+
const last = all.length - 1;
|
|
881
|
+
const index = event.key === 'Home' ? 0 : event.key === 'End' ? last : (current + (event.key === 'ArrowRight' ? 1 : last)) % all.length;
|
|
882
|
+
const next = all[index];
|
|
883
|
+
if (next === event.target) return;
|
|
884
|
+
memory().focusUntil = Date.now() + TAB_STRIP_FOCUS_WINDOW_MS;
|
|
885
|
+
next.focus?.({ preventScroll: true });
|
|
886
|
+
if (!isSelectedTab(next)) next.click?.();
|
|
887
|
+
schedule(update);
|
|
888
|
+
};
|
|
889
|
+
root.addEventListener?.('keydown', keydown);
|
|
890
|
+
const controller = { root, update, destroy() {
|
|
891
|
+
destroyed = true; root.removeEventListener?.('keydown', keydown); tabStrips.delete(root);
|
|
892
|
+
toggleWorkspaceClass(root, 'is-indicator-ready', false);
|
|
893
|
+
root.style?.removeProperty?.('--bb-tab-indicator-x'); root.style?.removeProperty?.('--bb-tab-indicator-width');
|
|
894
|
+
} };
|
|
895
|
+
tabStrips.set(root, controller);
|
|
896
|
+
schedule(update);
|
|
897
|
+
return controller;
|
|
898
|
+
}
|
|
899
|
+
|
|
786
900
|
/** The shared shallow dropdown chevron, sized and colored through shared CSS. */
|
|
787
901
|
export function workspaceDropdownChevron(doc) {
|
|
788
902
|
const wrap = el(doc, 'span', { className: 'bb-ws-combobox-chevron', attrs: { 'aria-hidden': 'true' } });
|
|
@@ -223,7 +223,7 @@
|
|
|
223
223
|
width: calc(var(--bb-world-panel-width) - var(--bb-world-right-inset));
|
|
224
224
|
overflow: hidden;
|
|
225
225
|
transform: translateX(calc(100% + 20px));
|
|
226
|
-
transition: transform .24s ease, visibility .24s;
|
|
226
|
+
transition: transform .24s var(--bb-ease-drawer, cubic-bezier(0.32, 0.72, 0, 1)), visibility .24s;
|
|
227
227
|
}
|
|
228
228
|
.bb-world-canvas-ui .bb-world-canvas-drawer.is-open { transform: translateX(0); }
|
|
229
229
|
.bb-world-canvas-ui .bb-world-canvas-panel-top {
|
|
@@ -320,7 +320,7 @@
|
|
|
320
320
|
overflow: hidden;
|
|
321
321
|
opacity: 0;
|
|
322
322
|
transform: translateY(24px);
|
|
323
|
-
transition: transform .24s ease, opacity .24s ease, visibility .24s;
|
|
323
|
+
transition: transform .24s var(--bb-ease-out, cubic-bezier(0.23, 1, 0.32, 1)), opacity .24s var(--bb-ease-out, cubic-bezier(0.23, 1, 0.32, 1)), visibility .24s;
|
|
324
324
|
}
|
|
325
325
|
.bb-world-canvas-ui .bb-world-canvas-help.is-open { opacity: 1; transform: translateY(0); }
|
|
326
326
|
.bb-world-canvas-ui .bb-world-canvas-help-body,
|