@principles/host-runtime 0.14.0 → 0.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,126 @@
1
+ import path from 'node:path';
2
+ import { computeBehaviorFacts, } from '@principles/core/runtime-v2';
3
+ import { assembleBehaviorHistory } from './behavior-history.js';
4
+ import { readWorkspaceRuleContextRowsBefore } from './workspace-behavior-evidence.js';
5
+ const HISTORY_LIMIT = 100;
6
+ const MAX_REASON_LENGTH = 240;
7
+ function isRecord(value) {
8
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
9
+ }
10
+ function unavailable(reason) {
11
+ const history = {
12
+ status: 'unavailable',
13
+ unavailableReason: reason.replace(/\s+/g, ' ').slice(0, MAX_REASON_LENGTH),
14
+ truncated: false,
15
+ calls: [],
16
+ };
17
+ return {
18
+ version: 2,
19
+ history,
20
+ facts: computeBehaviorFacts(history, null, null),
21
+ };
22
+ }
23
+ /**
24
+ * SPEC-RULECODE-HOST-PROMOTION-001 C: the WorkBuddy RuleContext provider.
25
+ *
26
+ * It reads the SAME canonical trajectory store the shared afterToolCall
27
+ * production path writes for WorkBuddy (`tool_calls` rows carrying the
28
+ * host's natural session/call ids and the observed project cwd) — genuinely
29
+ * observable WorkBuddy data, never borrowed Codex history. WorkBuddy has no
30
+ * design-gate declaration entry point (the Codex-native attestation source
31
+ * is Codex-only), so this provider deliberately supplies NO designGate
32
+ * fact: a rule whose required facts include design_approval stays suspended
33
+ * on this host with the precise `rule_required_fact_unavailable` warning
34
+ * instead of inheriting another host's attestation.
35
+ *
36
+ * Disabled, unscoped or unverifiable sources return explicit unavailable
37
+ * contexts — v2 rules then suspend through the existing shared-gate
38
+ * contract, which is the honest state until the missing input exists.
39
+ */
40
+ export function createWorkbuddyRuleContextProvider(options) {
41
+ const workspaceDir = path.resolve(options.workspaceDir);
42
+ const projectDir = options.projectDir !== undefined ? path.resolve(options.projectDir) : undefined;
43
+ return (request) => {
44
+ if (typeof request.sessionId !== 'string' || request.sessionId.trim().length === 0) {
45
+ return unavailable('session_id_invalid');
46
+ }
47
+ if (!options.enabled)
48
+ return unavailable('workbuddy_rule_context_disabled');
49
+ if (path.resolve(request.workspaceDir) !== workspaceDir)
50
+ return unavailable('workspace_scope_mismatch');
51
+ if (projectDir === undefined || !path.isAbsolute(projectDir)) {
52
+ return unavailable('workbuddy_project_scope_unavailable');
53
+ }
54
+ const raw = request.rawPayload;
55
+ const toolInput = isRecord(raw) && isRecord(raw.toolInput) ? raw.toolInput : null;
56
+ if (toolInput === null
57
+ || toolInput.toolName !== request.toolName
58
+ || !isRecord(toolInput.params)
59
+ || options.currentToolCallId.trim().length === 0) {
60
+ return unavailable('workbuddy_pre_tool_scope_mismatch');
61
+ }
62
+ const cutoff = options.cutoffAt;
63
+ if (!(cutoff instanceof Date) || !Number.isFinite(cutoff.getTime()))
64
+ return unavailable('history_cutoff_invalid');
65
+ try {
66
+ const historyRows = readWorkspaceRuleContextRowsBefore(workspaceDir, {
67
+ sessionId: request.sessionId,
68
+ projectDir,
69
+ beforeCreatedAt: cutoff.toISOString(),
70
+ excludeToolUseId: options.currentToolCallId,
71
+ limit: HISTORY_LIMIT,
72
+ // Review R2: consume ONLY rows PROVEN to be WorkBuddy's (stamped by
73
+ // this host's own writer). "Same workspace + same session id +
74
+ // same project" is NOT proof — a Codex session id colliding here
75
+ // must never lend its reads to a WorkBuddy read-before-write rule.
76
+ hostKind: 'workbuddy',
77
+ });
78
+ if (historyRows.unscopedPriorRows)
79
+ return unavailable('trajectory_project_scope_incomplete');
80
+ if ((historyRows.otherHostRows ?? 0) > 0) {
81
+ return unavailable('workbuddy_history_attribution_conflict');
82
+ }
83
+ if (historyRows.rows.length === 0) {
84
+ // Fail closed with the precise reason: legacy rows exist but cannot
85
+ // be PROVEN WorkBuddy's (never back-filled, never assumed).
86
+ if ((historyRows.unattributedRows ?? 0) > 0)
87
+ return unavailable('workbuddy_history_attribution_unprovable');
88
+ return unavailable('no_prior_session_history');
89
+ }
90
+ if ((historyRows.unattributedRows ?? 0) > 0) {
91
+ // Mixed window: consuming only the proven subset could UNDERCOUNT
92
+ // prior reads (a hidden foreign read would flip priorReadOfTarget),
93
+ // so the window is unprovable as a whole — suspend precisely.
94
+ return unavailable('workbuddy_history_attribution_unprovable');
95
+ }
96
+ const history = assembleBehaviorHistory(historyRows.rows, historyRows.truncated, {
97
+ projectDir,
98
+ toolSemantics: options.toolSemantics,
99
+ });
100
+ // WorkBuddy exposes its shell as the Bash tool, and MCP-style tools may
101
+ // resolve to 'other' absent from this host's semantic registry. Either
102
+ // may read or mutate files, so target-read absence and exact action
103
+ // counts cannot be asserted from this partial semantic view (same
104
+ // conservative rule as the Codex provider).
105
+ const factsIncomplete = history.truncated || history.calls.some((call) => call.canonicalKind === 'execute' || call.canonicalKind === 'other');
106
+ const computedFacts = computeBehaviorFacts(history, factsIncomplete ? null : request.targetPath, null);
107
+ const facts = factsIncomplete
108
+ ? {
109
+ priorReadOfTarget: 'unknown',
110
+ readCount: null,
111
+ writeCount: null,
112
+ uniqueWritePathCount: null,
113
+ sameActionBlockCount: null,
114
+ }
115
+ : computedFacts;
116
+ return {
117
+ version: 2,
118
+ history,
119
+ facts,
120
+ };
121
+ }
122
+ catch (error) {
123
+ return unavailable(`trajectory_history_unavailable:${error instanceof Error ? error.message : String(error)}`);
124
+ }
125
+ };
126
+ }
@@ -7,18 +7,35 @@ export declare function createWorkspaceBehaviorEvidencePort(workspaceDir: string
7
7
  * database. The timestamp is the caller's pre-event cutoff; rows at or after
8
8
  * it are excluded so replayed/future calls cannot enter a live RuleContext.
9
9
  * This is read-only and never creates or migrates trajectory state.
10
+ *
11
+ * Review R2 (SPEC-RULECODE-HOST-PROMOTION-001): when `hostKind` is supplied,
12
+ * the reader partitions the window by PROVEN producer attribution
13
+ * (`tool_calls.host_kind`, stamped by each host's writer) instead of handing
14
+ * back every row: `rows` carries only rows stamped with that host,
15
+ * `otherHostRows` counts rows stamped with a different host (a cross-host
16
+ * session-id collision), and `unattributedRows` counts legacy rows with no
17
+ * stamp (written before the column existed — attribution is unprovable, not
18
+ * assumed). A database whose tool_calls predates the column entirely counts
19
+ * every row in the unattributed bucket. The caller decides the failure
20
+ * policy; this reader never guesses an attribution.
10
21
  */
22
+ export interface WorkspaceRuleContextRowsResult {
23
+ rows: readonly RuleHostContextRow[];
24
+ truncated: boolean;
25
+ unscopedPriorRows: boolean;
26
+ /** Present only for attribution-aware reads: rows stamped with ANOTHER host (never zero-checked when hostKind is absent). */
27
+ otherHostRows?: number;
28
+ /** Present only for attribution-aware reads: legacy rows with no host stamp. */
29
+ unattributedRows?: number;
30
+ }
11
31
  export declare function readWorkspaceRuleContextRowsBefore(workspaceDir: string, input: {
12
32
  sessionId: string;
13
33
  projectDir: string;
14
34
  beforeCreatedAt: string;
15
35
  excludeToolUseId: string;
16
36
  limit: number;
17
- }): {
18
- rows: readonly RuleHostContextRow[];
19
- truncated: boolean;
20
- unscopedPriorRows: boolean;
21
- };
37
+ hostKind?: string;
38
+ }): WorkspaceRuleContextRowsResult;
22
39
  /**
23
40
  * List only Codex sessions proven by normalized host evidence and a matching
24
41
  * project-scoped trajectory row. The trajectory schema has no host_kind on
@@ -74,12 +74,6 @@ export function createWorkspaceBehaviorEvidencePort(workspaceDir, toolSemantics)
74
74
  },
75
75
  };
76
76
  }
77
- /**
78
- * Read one bounded, same-session history window from the canonical trajectory
79
- * database. The timestamp is the caller's pre-event cutoff; rows at or after
80
- * it are excluded so replayed/future calls cannot enter a live RuleContext.
81
- * This is read-only and never creates or migrates trajectory state.
82
- */
83
77
  export function readWorkspaceRuleContextRowsBefore(workspaceDir, input) {
84
78
  const { sessionId, projectDir, beforeCreatedAt, excludeToolUseId, limit } = input;
85
79
  if (sessionId.trim().length === 0)
@@ -95,9 +89,21 @@ export function readWorkspaceRuleContextRowsBefore(workspaceDir, input) {
95
89
  const db = new Database(path.join(workspaceDir, '.state', 'trajectory.db'), { readonly: true, fileMustExist: true });
96
90
  try {
97
91
  db.pragma('busy_timeout = 100');
92
+ const attributionAware = input.hostKind !== undefined;
93
+ // Select host_kind ONLY for attribution-aware reads on schemas that carry
94
+ // the column. A plain read (or a legacy schema without the column) keeps
95
+ // the historical column list — never a failing query.
96
+ const includeHostKind = attributionAware && (() => {
97
+ const columns = db.prepare('PRAGMA table_info(tool_calls)').all();
98
+ return Array.isArray(columns)
99
+ && columns.some((column) => record(column) && typeof column.name === 'string' && column.name === 'host_kind');
100
+ })();
98
101
  return db.transaction(() => {
99
- const rows = db.prepare(`
100
- SELECT id, tool_name, outcome, params_json
102
+ // Attribution-aware read: fetch one extra slot beyond the limit so the
103
+ // partition counts stay truthful about a truncated window's tail.
104
+ const selectColumns = includeHostKind ? 'id, tool_name, outcome, params_json, host_kind' : 'id, tool_name, outcome, params_json';
105
+ const fetched = db.prepare(`
106
+ SELECT ${selectColumns}
101
107
  FROM tool_calls
102
108
  WHERE session_id = ? AND project_dir = ? AND created_at < ? AND (tool_use_id IS NULL OR tool_use_id <> ?)
103
109
  ORDER BY created_at DESC, id DESC
@@ -108,12 +114,36 @@ export function readWorkspaceRuleContextRowsBefore(workspaceDir, input) {
108
114
  WHERE session_id = ? AND project_dir IS NULL AND created_at < ?
109
115
  AND (tool_use_id IS NULL OR tool_use_id <> ?) LIMIT 1
110
116
  `).get(sessionId, beforeCreatedAt, excludeToolUseId);
111
- if (!Array.isArray(rows))
117
+ if (!Array.isArray(fetched))
112
118
  throw new Error('history_query_invalid');
119
+ if (!attributionAware) {
120
+ return {
121
+ rows: fetched.slice(0, limit).reverse().map(contextRow),
122
+ truncated: fetched.length > limit,
123
+ unscopedPriorRows: unscoped !== undefined,
124
+ };
125
+ }
126
+ let otherHostRows = 0;
127
+ let unattributedRows = 0;
128
+ const matching = [];
129
+ for (const row of fetched) {
130
+ if (!record(row) || !Object.hasOwn(row, 'host_kind') || row.host_kind === null || row.host_kind === undefined) {
131
+ // No stamp (or no column): unprovable — never guessed into the host.
132
+ unattributedRows += 1;
133
+ continue;
134
+ }
135
+ if (row.host_kind !== input.hostKind) {
136
+ otherHostRows += 1;
137
+ continue;
138
+ }
139
+ matching.push(row);
140
+ }
113
141
  return {
114
- rows: rows.slice(0, limit).reverse().map(contextRow),
115
- truncated: rows.length > limit,
142
+ rows: matching.slice(0, limit).reverse().map(contextRow),
143
+ truncated: fetched.length > limit,
116
144
  unscopedPriorRows: unscoped !== undefined,
145
+ otherHostRows,
146
+ unattributedRows,
117
147
  };
118
148
  })();
119
149
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/host-runtime",
3
- "version": "0.14.0",
3
+ "version": "0.14.2",
4
4
  "description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -31,7 +31,7 @@
31
31
  "lint": "eslint \"src/**/*.ts\""
32
32
  },
33
33
  "dependencies": {
34
- "@principles/core": "^1.297.3",
34
+ "@principles/core": "^1.297.5",
35
35
  "@principles/install-layout": "^0.4.0",
36
36
  "better-sqlite3": "^13.0.3",
37
37
  "js-yaml": "^5.4.3"