@indigoai-us/hq-cli 5.345.248 → 5.345.250

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/contracts/host-canary-release.json +3 -3
  3. package/dist/command-catalog.generated.d.ts +93 -8
  4. package/dist/command-catalog.generated.js +114 -8
  5. package/dist/commands/core-job-run-native.js +4 -0
  6. package/dist/commands/core-knowledge-prefs.d.ts +1 -1
  7. package/dist/commands/core-knowledge-prefs.js +1 -16
  8. package/dist/commands/core.js +0 -2
  9. package/dist/commands/daemon.js +21 -0
  10. package/dist/commands/ontology-graph.d.ts +2 -1
  11. package/dist/commands/ontology-graph.js +41 -10
  12. package/dist/commands/sync-core.js +6 -0
  13. package/dist/fast-scaffold.js +1 -3
  14. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +281 -256
  15. package/dist/hq-cloud-sync-runner/package.json +1 -1
  16. package/dist/index.d.ts +8 -0
  17. package/dist/index.js +47 -0
  18. package/dist/lib/daemon/installed-cli-restart.d.ts +57 -0
  19. package/dist/lib/daemon/installed-cli-restart.js +114 -0
  20. package/dist/lib/daemon/legacy-journal-gate.d.ts +32 -0
  21. package/dist/lib/daemon/legacy-journal-gate.js +102 -0
  22. package/dist/lib/daemon/machine-checks.d.ts +7 -0
  23. package/dist/lib/daemon/machine-checks.js +10 -0
  24. package/dist/lib/daemon/run.d.ts +3 -1
  25. package/dist/lib/daemon/run.js +48 -5
  26. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  27. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  28. package/dist/lib/hook-engine/coverage.d.ts +82 -13
  29. package/dist/lib/hook-engine/coverage.js +214 -18
  30. package/dist/lib/hook-engine/registration-identity.d.ts +5 -0
  31. package/dist/lib/hook-engine/registration-identity.js +1 -1
  32. package/dist/lib/hook-engine/resolve.d.ts +23 -0
  33. package/dist/lib/hook-engine/resolve.js +48 -1
  34. package/dist/lib/hook-engine/stable-heal.d.ts +87 -0
  35. package/dist/lib/hook-engine/stable-heal.js +214 -0
  36. package/dist/lib/hot-channels/graph-context.js +4 -1
  37. package/dist/lib/ontology-graph/model/step.d.ts +2 -0
  38. package/dist/lib/ontology-graph/model/step.js +3 -0
  39. package/dist/lib/ontology-graph/org/derive.d.ts +2 -0
  40. package/dist/lib/ontology-graph/org/derive.js +9 -2
  41. package/dist/lib/ontology-graph/org/index.d.ts +35 -6
  42. package/dist/lib/ontology-graph/org/index.js +136 -19
  43. package/dist/lib/ontology-graph/org/text.d.ts +2 -0
  44. package/dist/lib/ontology-graph/org/text.js +6 -0
  45. package/dist/lib/ontology-graph/org/types.d.ts +5 -0
  46. package/dist/lib/ontology-graph/pages/render.d.ts +2 -0
  47. package/dist/lib/ontology-graph/pages/render.js +10 -4
  48. package/dist/lib/ontology-graph/read/brief.js +4 -1
  49. package/dist/lib/ontology-graph/read/index.js +13 -2
  50. package/dist/lib/ontology-graph/read/names.d.ts +6 -1
  51. package/dist/lib/ontology-graph/read/names.js +8 -3
  52. package/dist/lib/ontology-graph/replay/engine.d.ts +47 -1
  53. package/dist/lib/ontology-graph/replay/engine.js +68 -2
  54. package/dist/lib/ontology-graph/replay/index.d.ts +2 -1
  55. package/dist/lib/ontology-graph/replay/index.js +1 -1
  56. package/dist/lib/ontology-graph/schema/authority.d.ts +34 -0
  57. package/dist/lib/ontology-graph/schema/authority.js +29 -0
  58. package/dist/lib/ontology-graph/schema/index.d.ts +1 -1
  59. package/dist/lib/ontology-graph/schema/index.js +1 -1
  60. package/dist/lib/ontology-graph/types.d.ts +7 -0
  61. package/dist/lib/sync-core/engine-holds.d.ts +1 -1
  62. package/dist/lib/sync-core/engine-holds.js +12 -2
  63. package/dist/lib/sync-core/hand-back.d.ts +2 -1
  64. package/dist/lib/sync-core/hand-back.js +16 -2
  65. package/dist/lib/sync-core/legacy-journal-export-child.d.ts +2 -0
  66. package/dist/lib/sync-core/legacy-journal-export-child.js +24 -0
  67. package/dist/lib/sync-core/legacy-journal-export.d.ts +39 -0
  68. package/dist/lib/sync-core/legacy-journal-export.js +241 -0
  69. package/dist/lib/sync-core/legacy-journal-reader.d.ts +15 -0
  70. package/dist/lib/sync-core/legacy-journal-reader.js +56 -0
  71. package/dist/lib/sync-core/reconcile.d.ts +3 -0
  72. package/dist/lib/sync-core/reconcile.js +43 -3
  73. package/dist/utils/cli-telemetry.d.ts +1 -0
  74. package/dist/utils/cli-telemetry.js +6 -3
  75. package/dist/utils/hook-engine-rollup.d.ts +96 -0
  76. package/dist/utils/hook-engine-rollup.js +725 -0
  77. package/package.json +8 -8
  78. package/scripts/install-hook-engine.mjs +4 -0
  79. package/assets/scaffold/core/scripts/knowledge-prefs.sh +0 -55
@@ -0,0 +1,214 @@
1
+ /**
2
+ * After an update, heal the `stable` link core.next registrations name by
3
+ * re-running the gated reconcile, never by moving the link directly.
4
+ *
5
+ * `npm install -g @indigoai-us/hq-cli` pins the new engine and rewrites the
6
+ * `current` pointer. `stable` keeps naming the previous engine until
7
+ * `hq reindex` runs; until then read-only resolution refuses it and the doctor
8
+ * fails. The first real `hq` command after an update starts `hq reindex
9
+ * --repo-root <root>` in the background for each HQ root this machine
10
+ * registers on the new core. That is the same reconcile a person runs by hand:
11
+ * the host canary gate, the engine's capabilities and the holds decide per host
12
+ * whether its registrations stay on the new core or go back to the old
13
+ * dispatcher, and it moves `stable`. Until it has run, `stable` keeps the
14
+ * previous engine, which passed its own checks.
15
+ *
16
+ * The postinstall moves nothing ([`staleStableEngine`] only reports).
17
+ *
18
+ * The roots come from the `--hq-root` arguments in the user-scope hook files,
19
+ * so this starts an unattended `hq reindex` in any folder named there. That is
20
+ * no new boundary: only someone who can already write those files (and so
21
+ * already choose what every hook runs) can plant a root.
22
+ *
23
+ * `fleet-local` registrations are not host-canary gated (by design; see
24
+ * host-registration.ts `hostCanaryGate`), so on a fleet box the heal moves them
25
+ * to the new engine at the first command after an update, as a manual
26
+ * reindex would.
27
+ */
28
+ import { spawn as nodeSpawn } from 'node:child_process';
29
+ import * as fs from 'node:fs';
30
+ import { homedir } from 'node:os';
31
+ import * as path from 'node:path';
32
+ import { CORE_NEXT_LINK, hqRootArgument, userHookSettingsFile } from './registration-identity.js';
33
+ import { staleStableEngine } from './resolve.js';
34
+ import { resolveDefaultHqRoot } from '../../utils/hq-root-resolver.js';
35
+ /** Set in the reindex the heal starts, so that process does not start another. */
36
+ export const STABLE_HEAL_ENV = 'HQ_STABLE_HEAL';
37
+ /**
38
+ * Removed from the reindex's environment so the host canary gate applies in
39
+ * full: host-registration.ts `REINDEX_FROM_HOOK_ENV` (keeps every host on its
40
+ * current core) and canary-gate.ts `SKIP_CANARY_GATE_ENV` (bypasses the gate).
41
+ * Spelled out here so the start-up path does not load those modules;
42
+ * stable-heal.test.ts checks they match.
43
+ */
44
+ export const GATE_WEAKENING_ENV = ['HQ_REINDEX_FROM_HOOK', 'HQ_SKIP_HOST_CANARY_GATE'];
45
+ /** A heal for the same pinned engine is not started again within this window. */
46
+ export const STABLE_HEAL_RETRY_MS = 60 * 60 * 1000;
47
+ function statePath(home) {
48
+ return path.join(home, '.hq', 'state', 'stable-heal.json');
49
+ }
50
+ function readState(home) {
51
+ try {
52
+ return JSON.parse(fs.readFileSync(statePath(home), 'utf8'));
53
+ }
54
+ catch (error) {
55
+ if (error.code === 'ENOENT' || error instanceof SyntaxError)
56
+ return null;
57
+ throw error;
58
+ }
59
+ }
60
+ function writeState(home, pinned, at) {
61
+ const file = statePath(home);
62
+ fs.mkdirSync(path.dirname(file), { recursive: true });
63
+ const temp = `${file}.${process.pid}.tmp`;
64
+ fs.writeFileSync(temp, `${JSON.stringify({ pinned, at })}\n`);
65
+ fs.renameSync(temp, file);
66
+ }
67
+ /** Every `--hq-root` named by a new-core entry anywhere in `doc`. */
68
+ function coreNextRootsIn(doc, out) {
69
+ if (Array.isArray(doc)) {
70
+ for (const item of doc)
71
+ coreNextRootsIn(item, out);
72
+ return;
73
+ }
74
+ if (!doc || typeof doc !== 'object')
75
+ return;
76
+ const entry = doc;
77
+ if (typeof entry.command === 'string' && CORE_NEXT_LINK.test(entry.command)) {
78
+ const root = hqRootArgument(entry);
79
+ if (root)
80
+ out.push(root);
81
+ }
82
+ for (const value of Object.values(entry))
83
+ coreNextRootsIn(value, out);
84
+ }
85
+ /**
86
+ * The HQ roots to reconcile: each root a user-scope hook file (Claude Code,
87
+ * Codex, Grok Build) registers on the new core, and this machine's HQ root
88
+ * (`HQ_ROOT`, the root around the current folder, or the installer's record),
89
+ * whose project files and fleet profiles may name `stable` too. Only existing
90
+ * folders, each once.
91
+ */
92
+ export function stableHealRoots(home, env, cwd, platform) {
93
+ const named = [];
94
+ const files = [
95
+ userHookSettingsFile('claude', home, env),
96
+ userHookSettingsFile('codex', home, env),
97
+ path.join(home, '.grok', 'hooks', 'hq-hq-bridge.json'),
98
+ ];
99
+ for (const file of files) {
100
+ let text;
101
+ try {
102
+ text = fs.readFileSync(file, 'utf8');
103
+ }
104
+ catch (error) {
105
+ if (error.code === 'ENOENT')
106
+ continue;
107
+ throw error;
108
+ }
109
+ let doc;
110
+ try {
111
+ doc = JSON.parse(text);
112
+ }
113
+ catch {
114
+ // An unreadable hook file names no root; reindex reports it.
115
+ continue;
116
+ }
117
+ coreNextRootsIn(doc, named);
118
+ }
119
+ try {
120
+ named.push(resolveDefaultHqRoot({ onMissing: 'throw', env, cwd, home, platform }));
121
+ }
122
+ catch {
123
+ // No HQ root on this machine beyond the ones the hook files name.
124
+ }
125
+ const seen = new Set();
126
+ const roots = [];
127
+ for (const root of named) {
128
+ let real;
129
+ try {
130
+ real = fs.realpathSync(root);
131
+ }
132
+ catch {
133
+ continue;
134
+ }
135
+ if (!fs.statSync(real).isDirectory() || seen.has(real))
136
+ continue;
137
+ seen.add(real);
138
+ roots.push(root);
139
+ }
140
+ return roots;
141
+ }
142
+ /**
143
+ * Append a heal that threw to `~/.hq/logs/stable-heal.log`. The command the
144
+ * person ran goes on, and stderr stays clean for the hooks that call hq; the
145
+ * doctor still reports the stale link until a reindex moves it.
146
+ */
147
+ export function recordStableHealFailure(error, home = homedir(), now = Date.now()) {
148
+ try {
149
+ const logDir = path.join(home, '.hq', 'logs');
150
+ fs.mkdirSync(logDir, { recursive: true });
151
+ fs.appendFileSync(path.join(logDir, 'stable-heal.log'), `${new Date(now).toISOString()} heal failed: ${error instanceof Error ? error.message : String(error)}\n`);
152
+ }
153
+ catch {
154
+ // Nowhere left to record it; hq doctor reports the stale link.
155
+ }
156
+ }
157
+ /**
158
+ * Start the gated reconcile for every HQ root when `stable` no longer names
159
+ * this CLI's pinned engine. Once per pinned engine per hour, whatever the
160
+ * outcome, so a reindex that cannot finish (another holds the root's lock, the
161
+ * gate refuses) does not run on every command. The child runs plain
162
+ * `hq reindex --repo-root <root> --lock-timeout 0` one root after another,
163
+ * with the variables that would weaken the gate removed from its environment.
164
+ */
165
+ export function healStableEngine(options = {}) {
166
+ const env = options.env ?? process.env;
167
+ const home = options.home ?? homedir();
168
+ const platform = options.platform ?? process.platform;
169
+ if (env[STABLE_HEAL_ENV] === '1')
170
+ return { stale: null, roots: [], skipped: 'already inside a heal' };
171
+ // Windows keeps shell registrations (coreNextOffReason); no new-core entry names stable there.
172
+ if (platform === 'win32')
173
+ return { stale: null, roots: [], skipped: 'Windows keeps shell registration' };
174
+ const stale = staleStableEngine({ ...options.lookup, home, platform });
175
+ if (!stale)
176
+ return { stale: null, roots: [] };
177
+ const now = (options.now ?? Date.now)();
178
+ const last = readState(home);
179
+ if (last && last.pinned === stale.pinned && typeof last.at === 'number' && now - last.at >= 0 && now - last.at < STABLE_HEAL_RETRY_MS) {
180
+ return { stale, roots: [], skipped: 'a heal for this engine started less than an hour ago' };
181
+ }
182
+ const roots = stableHealRoots(home, env, options.cwd ?? process.cwd(), platform);
183
+ if (!roots.length)
184
+ return { stale, roots: [], skipped: 'no HQ root to reconcile' };
185
+ const cliEntry = options.cliEntry ?? process.argv[1];
186
+ if (!cliEntry)
187
+ return { stale, roots: [], skipped: 'no CLI entry to run' };
188
+ writeState(home, stale.pinned, now);
189
+ const childEnv = { ...env, [STABLE_HEAL_ENV]: '1', HQ_INSTALL_FOLLOWUP: '1' };
190
+ for (const name of GATE_WEAKENING_ENV)
191
+ delete childEnv[name];
192
+ const logDir = path.join(home, '.hq', 'logs');
193
+ fs.mkdirSync(logDir, { recursive: true });
194
+ const log = fs.openSync(path.join(logDir, 'stable-heal.log'), 'a');
195
+ try {
196
+ fs.writeSync(log, `${new Date(now).toISOString()} stable ${stale.resolved ?? '(dangling)'} -> pinned ${stale.pinned}; hq reindex for ${roots.join(', ')}\n`);
197
+ const script = [
198
+ "const { spawnSync } = require('node:child_process');",
199
+ 'const [cli, ...roots] = process.argv.slice(1);',
200
+ "for (const root of roots) spawnSync(process.execPath, [cli, 'reindex', '--repo-root', root, '--lock-timeout', '0'], { stdio: 'inherit' });",
201
+ ].join('\n');
202
+ const child = (options.spawn ?? nodeSpawn)(options.execPath ?? process.execPath, ['-e', script, cliEntry, ...roots], {
203
+ detached: true,
204
+ stdio: ['ignore', log, log],
205
+ env: childEnv,
206
+ });
207
+ child.unref();
208
+ }
209
+ finally {
210
+ fs.closeSync(log);
211
+ }
212
+ return { stale, roots };
213
+ }
214
+ //# sourceMappingURL=stable-heal.js.map
@@ -35,7 +35,7 @@
35
35
  * for the company (`openSignalsGraphContext` returns null otherwise).
36
36
  */
37
37
  import * as path from "node:path";
38
- import { originTier } from "../ontology-graph/schema/index.js";
38
+ import { isUnverifiedGuess, originTier } from "../ontology-graph/schema/index.js";
39
39
  import { GraphCompanyMismatchError, GraphCompanyStampError, GraphCompanyUnclaimedError, assertGraphWritableFor, openGraphStore, resolveGraphRoot } from "../ontology-graph/store/index.js";
40
40
  import { COMPANY_AUDIENCE, } from "../ontology-graph/types.js";
41
41
  import { graphExists, loadReadIndex, normalizeName, rowVisible, visible, } from "../ontology-graph/read/graph-index.js";
@@ -236,6 +236,9 @@ function mainEdges(session, ref, filter, cap) {
236
236
  return rows
237
237
  .filter((stored) => stored.row.kind === "E" && !stored.row.valid.to && rowVisible(stored.audience, filter))
238
238
  .filter((stored) => session.schema.link_types[stored.row.verb]?.class === "state")
239
+ // An employer a model guessed at low confidence is not sent to the next model as a relationship:
240
+ // a pack line carries no origin or confidence, so it would read as established.
241
+ .filter((stored) => !isUnverifiedGuess(stored.row, { edges: true }))
239
242
  .filter((stored) => {
240
243
  const target = session.index.entities[session.index.byId.get(stored.row.target) ?? -1];
241
244
  return target !== undefined && visible(target, filter);
@@ -139,6 +139,8 @@ export interface RunTotals {
139
139
  wallMs: number;
140
140
  /** Cache hits / (cache hits + items sent to the model). 1 when nothing was sent. */
141
141
  cacheHitRate: number;
142
+ /** Items this step left pending, by why. `budget-day` is the daily cap, `budget-run` the run's own cap. */
143
+ pendingByReason: Partial<Record<PendingReason, number>>;
142
144
  }
143
145
  /** The step as this package's tasks use it. A superset of the contract's `ModelStep`. */
144
146
  export interface BatchModelStep extends ModelStep {
@@ -91,6 +91,7 @@ export function createBatchModelStep(config) {
91
91
  calls: 0, cacheHits: 0, pending: 0, errors: 0, used: zero(),
92
92
  };
93
93
  const total = { calls: 0, cacheHits: 0, pending: 0, parked: 0, errors: 0, used: zero(), estimatedCalls: 0, wallMs: 0, sent: 0 };
94
+ const pendingByReason = {};
94
95
  let haltReason = null;
95
96
  let budgetStopped = false;
96
97
  let errorsInARow = 0;
@@ -120,6 +121,7 @@ export function createBatchModelStep(config) {
120
121
  pendingDirty = true;
121
122
  window.pending += 1;
122
123
  total.pending += 1;
124
+ pendingByReason[marker.reason] = (pendingByReason[marker.reason] ?? 0) + 1;
123
125
  };
124
126
  const park = (record) => {
125
127
  const full = { ...record, at: now().toISOString() };
@@ -513,6 +515,7 @@ export function createBatchModelStep(config) {
513
515
  estimatedCalls: total.estimatedCalls,
514
516
  wallMs: total.wallMs,
515
517
  cacheHitRate: asked === 0 ? 1 : total.cacheHits / asked,
518
+ pendingByReason: { ...pendingByReason },
516
519
  };
517
520
  },
518
521
  halted() {
@@ -44,6 +44,8 @@ export interface Derived {
44
44
  /** Subjects named by so many decisions that sharing one says nothing. */
45
45
  genericSubjects: Set<EntityRef>;
46
46
  }
47
+ /** Engineering's share of a commit to a repository named for another kind of work. */
48
+ export declare const COMMIT_ENGINEERING_SHARE_NAMED_REPO = 0.25;
47
49
  /** How much of a decision's wording an action item must share before it counts as carrying that decision out. */
48
50
  export declare const CARRIES_OUT_SIMILARITY = 0.15;
49
51
  /** The weight of a class as evidence about `person`. */
@@ -1,5 +1,7 @@
1
1
  import { DECISION_DIRECTS, NameIndex, addDays, areasOf, clip, continuesWithSecondOwner, directHits, excerptAt, similarity, looksAutomated, namesSubject, ownsAction, saysLed, saysPresented, } from "./text.js";
2
2
  import { ACTIVITY_KINDS, AREAS, ORG_WINDOWS, SKEW_WEIGHTS, WINDOW_DAYS, } from "./types.js";
3
+ /** Engineering's share of a commit to a repository named for another kind of work. */
4
+ export const COMMIT_ENGINEERING_SHARE_NAMED_REPO = 0.25;
3
5
  const DIRECT_TYPES = new Set(["action_item", "decision", "participant_contribution", "summary", "commitment", "key_point", "question"]);
4
6
  /** How much one act says about the person's area of work. */
5
7
  const AREA_WEIGHT = { decision: 1, action: 1, commitment: 1, contribution: 0.5, thread: 0.5, question: 0.3, attended: 0.3, external: 0.6, session: 0.5 };
@@ -52,9 +54,14 @@ export function deriveActs(graph) {
52
54
  delete about.engineering;
53
55
  const others = Object.entries(about);
54
56
  const total = others.reduce((sum, [, share]) => sum + share, 0);
55
- const areas = { engineering: others.length > 0 ? 0.5 : 1 };
57
+ // A repository whose own name says what it is for (a marketing site, a design system) holds
58
+ // that kind of work first: the commit is the means, and engineering keeps a quarter of it.
59
+ const repoAbout = areasOf(commit.repo.replace(/[-_]/g, " "));
60
+ delete repoAbout.engineering;
61
+ const base = others.length === 0 ? 1 : Object.keys(repoAbout).length > 0 ? COMMIT_ENGINEERING_SHARE_NAMED_REPO : 0.5;
62
+ const areas = { engineering: base };
56
63
  for (const [area, share] of others)
57
- areas[area] = (0.5 * share) / total;
64
+ areas[area] = ((1 - base) * share) / total;
58
65
  act({
59
66
  person: commit.person, kind: "commits", date: commit.date, text: commit.text, src: commit.src, cls: "code", count: commit.count,
60
67
  subjects: commit.project ? [commit.project] : [], repo: commit.repo, areas, areaWeight: Math.min(5, Math.log2(1 + commit.count)) * (automated ? 0.1 : 1),
@@ -1,5 +1,5 @@
1
1
  import type { AudienceKey, CommandOutput, GraphContext, GraphStore } from "../types.js";
2
- import { type DerivedRow, type ObservedOrg, type ObservedPerson, type OrgOptions, type OrgPersonOptions, type OrgView } from "./types.js";
2
+ import { type DerivedRow, type ObservedOrg, type ObservedPerson, type OrgOptions, type OrgPersonOptions, type OrgView, type OrgWindow } from "./types.js";
3
3
  import type { RosterFile } from "../resolve/roster.js";
4
4
  export * from "./types.js";
5
5
  export { loadOrgGraph, audiencesOf, classifySource, planFolds } from "./load.js";
@@ -25,8 +25,24 @@ export declare const KNOWN_LIMITS: readonly string[];
25
25
  export declare function hedgedRole(person: ObservedPerson): string;
26
26
  /** Computes the observed org for one view. Writes nothing. */
27
27
  export declare function buildObservedOrg(contextIn: GraphContext, options?: OrgOptions, internals?: BuildInternals): Promise<ObservedOrg>;
28
- /** Flattens an observed org into derived rows. Pure. */
29
- export declare function derivedRows(org: ObservedOrg): DerivedRow[];
28
+ /** Row kinds that state a role, a line of direction or a stated-versus-observed finding. Kept out unless roles are asked for. */
29
+ export declare const ROLE_ROW_KINDS: ReadonlySet<DerivedRow["kind"]>;
30
+ /** The part of an observed org that is about what people do: no role lines, no direction edges, no stated claims. */
31
+ export declare function activityOnly(org: ObservedOrg): Omit<ObservedOrg, "people" | "owners" | "directs" | "disagreements" | "stated"> & {
32
+ people: (Omit<ObservedPerson, "role"> & {
33
+ mainAreas: ObservedPerson["role"]["mainAreas"];
34
+ change: ObservedPerson["role"]["change"];
35
+ })[];
36
+ owners: Omit<ObservedOrg["owners"][number], "listed" | "agrees">[];
37
+ };
38
+ /** Kinds of act that say who directs or approves whose work. Shown and stored only when roles are asked for. */
39
+ export declare const DIRECTION_KINDS: ReadonlySet<string>;
40
+ /** A person with every count and example of a direction or approval kind taken out. */
41
+ export declare function withoutDirection(person: ObservedPerson): ObservedPerson;
42
+ /** Flattens an observed org into derived rows. Pure. Role, direction and disagreement rows only with `roles`. */
43
+ export declare function derivedRows(org: ObservedOrg, options?: {
44
+ roles?: boolean;
45
+ }): DerivedRow[];
30
46
  export declare function derivedDir(graphRoot: string, audience: AudienceKey): string;
31
47
  export interface WriteResult {
32
48
  dir: string;
@@ -38,7 +54,9 @@ export interface WriteResult {
38
54
  * Like every writer it first claims the folder for the company, and refuses a
39
55
  * folder that belongs to another company or an observed org built for another one.
40
56
  */
41
- export declare function writeObservedOrg(context: Pick<GraphContext, "graphRoot" | "company" | "companyRoot">, org: ObservedOrg): WriteResult;
57
+ export declare function writeObservedOrg(context: Pick<GraphContext, "graphRoot" | "company" | "companyRoot">, org: ObservedOrg, options?: {
58
+ roles?: boolean;
59
+ }): WriteResult;
42
60
  /** The derived rows a reader may see: the company folder, and the member's folder only when the reader is that member. */
43
61
  export declare function readDerivedRows(context: Pick<GraphContext, "graphRoot" | "company" | "companyRoot">, audiences: readonly AudienceKey[]): DerivedRow[];
44
62
  /**
@@ -61,9 +79,20 @@ export declare function directsOf(org: ObservedOrg, ref: string): {
61
79
  export declare function collaboratorsOf(org: ObservedOrg, ref: string, limit?: number): string[];
62
80
  export declare function renderHeader(org: ObservedOrg): string[];
63
81
  export declare function renderObservedTable(org: ObservedOrg): string[];
64
- export declare function renderObserved(org: ObservedOrg): string;
82
+ /** The kinds of work seen for a person in one window, each with its count. */
83
+ export declare function workLine(person: ObservedPerson, window?: OrgWindow): string;
84
+ export declare function shipsLine(person: ObservedPerson, window?: OrgWindow): string;
85
+ export declare function ownsLine(org: ObservedOrg, ref: string): string;
86
+ /** The default table: what each person does. No role line and no direction between people. */
87
+ export declare function renderActivityTable(org: ObservedOrg): string[];
88
+ export declare const ROLES_LEFT_OUT = "Role lines, direction between people and the stated-versus-observed comparison are left out. Add --roles to see the first two, or --compare for the comparison.";
89
+ export declare function renderObserved(org: ObservedOrg, options?: {
90
+ roles?: boolean;
91
+ }): string;
65
92
  export declare function renderCompare(org: ObservedOrg, limit?: number): string;
66
- export declare function renderPerson(org: ObservedOrg, person: ObservedPerson): string;
93
+ export declare function renderPerson(org: ObservedOrg, person: ObservedPerson, options?: {
94
+ roles?: boolean;
95
+ }): string;
67
96
  /** `hq ontology org observed`: compute and print the observed org. Stores the derived rows only when `write` is set. */
68
97
  export declare function orgObservedCommand(context: GraphContext, options?: OrgOptions): Promise<CommandOutput>;
69
98
  /** `hq ontology org compare`: stated versus observed. Writes nothing unless `write` is set. */
@@ -71,9 +71,9 @@ function honestyNotes(view, org, skewedShare, byClass) {
71
71
  }
72
72
  /** Where the derivation is known to be weak. Printed with every command output and stored with the view. */
73
73
  export const KNOWN_LIMITS = [
74
- "Commits count as at least half software engineering whatever the repository, so marketing-site, content and design work shipped as commits reads as engineering.",
74
+ "A commit counts as mostly software engineering unless the repository's own name says otherwise, so content and design work shipped in a product repository reads as engineering.",
75
75
  "Finance and operations work can read as deals, pricing and partnerships, because the same words appear in both.",
76
- "An action item filed under a meeting's host and not under a named person is counted for the host.",
76
+ "An action item a transcript files under a speaker label (Host, Speaker) and not a name is counted for nobody, so the person who took it looks less active.",
77
77
  "A bare first name that fits more than one roster member is not matched to either and shows as a separate person.",
78
78
  ];
79
79
  /** A role line with its status attached, for a table cell or a stored row read out of context. */
@@ -213,8 +213,34 @@ async function safeResolveMember(context) {
213
213
  // Derived rows on disk
214
214
  // ---------------------------------------------------------------------------
215
215
  const rowIdOf = (parts) => createHash("sha256").update(parts.join("\n")).digest("hex").slice(0, 12);
216
- /** Flattens an observed org into derived rows. Pure. */
217
- export function derivedRows(org) {
216
+ /** Row kinds that state a role, a line of direction or a stated-versus-observed finding. Kept out unless roles are asked for. */
217
+ export const ROLE_ROW_KINDS = new Set(["observed_role", "directs", "disagreement"]);
218
+ /** The part of an observed org that is about what people do: no role lines, no direction edges, no stated claims. */
219
+ export function activityOnly(org) {
220
+ const { directs: _directs, disagreements: _disagreements, stated: _stated, people, owners, ...rest } = org;
221
+ return {
222
+ ...rest,
223
+ people: people.map(withoutDirection).map(({ role, ...person }) => ({ ...person, mainAreas: role.mainAreas, change: role.change })),
224
+ // The listed owner and whether it agrees are stated claims: part of the comparison, not of what people do.
225
+ owners: owners.map(({ listed: _listed, agrees: _agrees, ...owner }) => owner),
226
+ };
227
+ }
228
+ /** Kinds of act that say who directs or approves whose work. Shown and stored only when roles are asked for. */
229
+ export const DIRECTION_KINDS = new Set(["directions_given", "directions_received", "approvals_given"]);
230
+ /** A person with every count and example of a direction or approval kind taken out. */
231
+ export function withoutDirection(person) {
232
+ const keep = (record) => Object.fromEntries(Object.entries(record).filter(([kind]) => !DIRECTION_KINDS.has(kind)));
233
+ const windows = Object.fromEntries(Object.entries(person.windows).map(([window, profile]) => [window, { ...profile, counts: keep(profile.counts) }]));
234
+ return { ...person, windows, examples: keep(person.examples) };
235
+ }
236
+ /** Flattens an observed org into derived rows. Pure. Role, direction and disagreement rows only with `roles`. */
237
+ export function derivedRows(org, options = {}) {
238
+ if (options.roles === true)
239
+ return allDerivedRows(org);
240
+ // Without roles the activity rows carry no direction or approval counts and cite no such example.
241
+ return allDerivedRows({ ...org, people: org.people.map(withoutDirection) }).filter((row) => !ROLE_ROW_KINDS.has(row.kind));
242
+ }
243
+ function allDerivedRows(org) {
218
244
  const { asOf, audience } = org.meta;
219
245
  const rows = [];
220
246
  const base = { learned: asOf, inferred: true, basis: "behavior", audience };
@@ -285,15 +311,15 @@ export function derivedDir(graphRoot, audience) {
285
311
  * Like every writer it first claims the folder for the company, and refuses a
286
312
  * folder that belongs to another company or an observed org built for another one.
287
313
  */
288
- export function writeObservedOrg(context, org) {
314
+ export function writeObservedOrg(context, org, options = {}) {
289
315
  if (org.meta.company !== context.company)
290
316
  throw new Error(`ontology graph: an observed org built for ${org.meta.company} cannot be stored in the graph of ${context.company}`);
291
317
  claimGraphRootFor(context.graphRoot, context.company, context.companyRoot);
292
318
  const dir = derivedDir(context.graphRoot, org.meta.audience);
293
319
  fs.mkdirSync(dir, { recursive: true });
294
- const rows = derivedRows(org);
320
+ const rows = derivedRows(org, options);
295
321
  const changedRows = atomicWriteFile(path.join(dir, "rows.jsonl"), rows.map((row) => JSON.stringify(row)).join("\n") + (rows.length > 0 ? "\n" : ""));
296
- const changedOrg = atomicWriteFile(path.join(dir, "observed.json"), `${JSON.stringify(org, null, 1)}\n`);
322
+ const changedOrg = atomicWriteFile(path.join(dir, "observed.json"), `${JSON.stringify(options.roles === true ? org : activityOnly(org), null, 1)}\n`);
297
323
  return { dir, rows: rows.length, changed: changedRows || changedOrg };
298
324
  }
299
325
  /** The derived rows a reader may see: the company folder, and the member's folder only when the reader is that member. */
@@ -349,7 +375,7 @@ export function collaboratorsOf(org, ref, limit = 3) {
349
375
  .map((edge) => `${nameIn(org, edge.a === ref ? edge.b : edge.a)} (${edge.score})`);
350
376
  }
351
377
  export function renderHeader(org) {
352
- const out = [`Observed org (${org.meta.company}), ${org.meta.view} view, as of ${org.meta.asOf}. Inferred from behavior; filed under audience ${org.meta.audience}.`, ""];
378
+ const out = [`Observed activity (${org.meta.company}), ${org.meta.view} view, as of ${org.meta.asOf}. Inferred from behavior; filed under audience ${org.meta.audience}.`, ""];
353
379
  for (const note of org.meta.honesty)
354
380
  out.push(`- ${note}`);
355
381
  out.push("", "Known limits of this derivation. Every line below is inferred and can be wrong in these ways:");
@@ -370,9 +396,47 @@ export function renderObservedTable(org) {
370
396
  }
371
397
  return out;
372
398
  }
373
- export function renderObserved(org) {
399
+ const WORK_KINDS = [
400
+ ["commits", "commits"],
401
+ ["decisions", "decisions"],
402
+ ["action_items", "action items"],
403
+ ["commitments", "commitments"],
404
+ ["meetings_attended", "meetings"],
405
+ ["meetings_led", "meetings led"],
406
+ ["external_meetings", "outside calls"],
407
+ ["threads_started", "threads started"],
408
+ ];
409
+ /** The kinds of work seen for a person in one window, each with its count. */
410
+ export function workLine(person, window = "90d") {
411
+ const counts = person.windows[window].counts;
412
+ const parts = WORK_KINDS.filter(([kind]) => counts[kind] > 0).map(([kind, label]) => `${label} ${counts[kind]}`);
413
+ return parts.length > 0 ? `seen in the rows: ${parts.join("; ")}` : "nothing seen";
414
+ }
415
+ export function shipsLine(person, window = "90d") {
416
+ const repos = person.windows[window].repos.slice(0, 4);
417
+ return repos.length > 0 ? repos.map((item) => `${item.name} (${item.count} commits)`).join(", ") : "-";
418
+ }
419
+ export function ownsLine(org, ref) {
420
+ const owned = org.owners.filter((owner) => owner.owner === ref).slice(0, 4);
421
+ return owned.length > 0 ? owned.map((owner) => `appears to own ${owner.subjectName} (${owner.events} events, confidence ${owner.conf.toFixed(2)})`).join(", ") : "-";
422
+ }
423
+ /** The default table: what each person does. No role line and no direction between people. */
424
+ export function renderActivityTable(org) {
425
+ const out = [
426
+ "| Person | Work, last 90 days (counts) | Main areas | Ships to (90d) | Owns (inferred) | Works most with (score) | Change over time | Evidence (90d / 365d / all) |",
427
+ "| --- | --- | --- | --- | --- | --- | --- | --- |",
428
+ ];
429
+ for (const person of org.people) {
430
+ const tag = person.actsInternal ? (person.maybe.length > 0 ? ` (not on roster; may be ${person.maybe.map((ref) => nameIn(org, ref)).join(" or ")})` : " (not on roster)") : person.isMember ? " (this member)" : "";
431
+ out.push(`| ${cell(person.name)}${tag} | ${cell(workLine(person))} | ${cell(areasLine(person))} | ${cell(shipsLine(person))} | ${cell(ownsLine(org, person.ref))} | ${cell(collaboratorsOf(org, person.ref).join(", ") || "-")} | ${cell(person.role.change?.text ?? "-")} | ${Math.round(person.windows["90d"].evidence)} / ${Math.round(person.windows["365d"].evidence)} / ${Math.round(person.windows.all.evidence)} |`);
432
+ }
433
+ return out;
434
+ }
435
+ export const ROLES_LEFT_OUT = "Role lines, direction between people and the stated-versus-observed comparison are left out. Add --roles to see the first two, or --compare for the comparison.";
436
+ export function renderObserved(org, options = {}) {
437
+ const roles = options.roles === true;
374
438
  const out = renderHeader(org);
375
- out.push(...renderObservedTable(org), "");
439
+ out.push(...(roles ? renderObservedTable(org) : renderActivityTable(org)), "");
376
440
  out.push("Working groups (clusters of who works with whom, named by what they work on):");
377
441
  for (const group of org.groups)
378
442
  out.push(`- ${group.id} ${group.name}: ${group.members.map((ref) => nameIn(org, ref)).join(", ")} (cohesion ${group.cohesion}, confidence ${group.conf.toFixed(2)})`);
@@ -383,14 +447,14 @@ export function renderObserved(org) {
383
447
  for (const bridge of org.bridges)
384
448
  out.push(`- ${nameIn(org, bridge.person)} (${bridge.home}): carries ${bridge.to.map((item) => `${Math.round(item.share * 100)}% of the collaboration between ${bridge.home} and ${item.group}`).join(", ")}`);
385
449
  }
386
- out.push("", "De facto owners, last 90 days, inferred from decisive activity (listed owner beside it):");
450
+ out.push("", `De facto owners, last 90 days, inferred from decisive activity${roles ? " (listed owner beside it)" : ""}:`);
387
451
  for (const owner of org.owners.slice(0, 25)) {
388
452
  const first = owner.candidates[0];
389
453
  const who = owner.verdict === "clear" && first ? `appears to be ${nameIn(org, first.person)} (${Math.round(first.share * 100)}% of decisive activity)` : owner.verdict === "shared" ? "appears shared by " + owner.candidates.slice(0, 2).map((candidate) => `${nameIn(org, candidate.person)} (${Math.round(candidate.share * 100)}%)`).join(" and ") : `no clear owner (most active: ${owner.candidates.slice(0, 2).map((candidate) => `${nameIn(org, candidate.person)} ${Math.round(candidate.share * 100)}%`).join(", ")})`;
390
454
  const listed = owner.listed.length > 0 ? owner.listed.map((claim) => claim.value).join(", ") : "none listed";
391
- out.push(`- ${owner.subjectName} [${owner.kind}]: ${who}; listed: ${listed}${owner.agrees === false ? " (disagrees)" : ""}; ${owner.events} events, confidence ${owner.conf.toFixed(2)}`);
455
+ out.push(`- ${owner.subjectName} [${owner.kind}]: ${who}${roles ? `; listed: ${listed}${owner.agrees === false ? " (disagrees)" : ""}` : ""}; ${owner.events} events, confidence ${owner.conf.toFixed(2)}`);
392
456
  }
393
- out.push("", `${org.disagreements.length} disagreements between stated and observed. Run \`hq ontology org compare\` to read them.`);
457
+ out.push("", roles ? `${org.disagreements.length} disagreements between stated and observed. Run \`hq ontology activity --compare\` to read them.` : ROLES_LEFT_OUT);
394
458
  return out.join("\n");
395
459
  }
396
460
  export function renderCompare(org, limit = 40) {
@@ -411,7 +475,47 @@ export function renderCompare(org, limit = 40) {
411
475
  out.push("No disagreement found in this view.");
412
476
  return out.join("\n");
413
477
  }
414
- export function renderPerson(org, person) {
478
+ export function renderPerson(org, person, options = {}) {
479
+ return options.roles === true ? renderPersonWithRoles(org, person) : renderPersonActivity(org, person);
480
+ }
481
+ /** One person, by what they do: work by window, what they ship and own, who they work with, change over time. */
482
+ function renderPersonActivity(org, whole) {
483
+ const person = withoutDirection(whole);
484
+ const out = renderHeader(org);
485
+ out.push(`${person.name} (${person.ref})${person.onRoster ? "" : ", not on the roster"}${person.isMember ? ", the member this graph was built for" : ""}`);
486
+ out.push(`Coverage: ${person.coverage.line}`);
487
+ for (const fold of person.folded)
488
+ out.push(`Folded in for this computation: ${fold.ref} (${fold.reason}).`);
489
+ out.push("", `Main areas (inferred from the mix of work): ${areasLine(person)}`);
490
+ out.push("", "Work by window:");
491
+ out.push("| Window | Commits | Decisions | Action items | Commitments | Meetings (led / outside) | Threads | Evidence |", "| --- | --- | --- | --- | --- | --- | --- | --- |");
492
+ for (const window of ["30d", "90d", "365d", "all"]) {
493
+ const c = person.windows[window].counts;
494
+ out.push(`| ${window} | ${c.commits} | ${c.decisions} | ${c.action_items} | ${c.commitments} | ${c.meetings_attended} (${c.meetings_led} / ${c.external_meetings}) | ${c.threads_started} | ${Math.round(person.windows[window].evidence)} |`);
495
+ }
496
+ out.push("", `Change over time: ${person.role.change ? `${person.role.change.text} [${person.role.change.cites.join(", ")}]` : "no change visible between the last 90 days and the nine months before"}`);
497
+ const year = person.windows["365d"];
498
+ if (year.repos.length > 0)
499
+ out.push("", `Ships to (365d): ${year.repos.map((item) => `${item.name} ${item.count}`).join(", ")}`);
500
+ if (year.projects.length > 0)
501
+ out.push(`Projects (365d): ${year.projects.map((item) => `${item.name} ${item.count}`).join(", ")}`);
502
+ if (year.customers.length > 0)
503
+ out.push(`Customers (365d): ${year.customers.map((item) => `${item.name} ${item.count}`).join(", ")}`);
504
+ if (person.isMember && (year.counts.own_sessions > 0 || year.counts.own_tracker > 0))
505
+ out.push(`Own sessions ${year.counts.own_sessions}, own tracker items ${year.counts.own_tracker} (365d): visible only on this machine, never compared with other people.`);
506
+ out.push("", `Owns (inferred): ${ownsLine(org, person.ref) === "-" ? "nothing observed" : ownsLine(org, person.ref)}`);
507
+ out.push(`Works most with: ${collaboratorsOf(org, person.ref, 5).join(", ") || "no one observed"}`);
508
+ const group = org.groups.find((item) => item.members.includes(person.ref));
509
+ if (group)
510
+ out.push(`Working group (inferred): ${group.id} ${group.name}`);
511
+ out.push("", "Examples:");
512
+ for (const [kind, list] of Object.entries(person.examples))
513
+ for (const example of (list ?? []).slice(0, 2))
514
+ out.push(`- ${kind} ${example.date}: ${example.text} (${example.src}; ${classWords(example.cls)})`);
515
+ out.push("", ROLES_LEFT_OUT);
516
+ return out.join("\n");
517
+ }
518
+ function renderPersonWithRoles(org, person) {
415
519
  const out = renderHeader(org);
416
520
  out.push(`${person.name} (${person.ref})${person.onRoster ? "" : ", not on the roster"}${person.isMember ? ", the member this graph was built for" : ""}`);
417
521
  out.push(`Coverage: ${person.coverage.line}`);
@@ -472,9 +576,10 @@ export function renderPerson(org, person) {
472
576
  /** `hq ontology org observed`: compute and print the observed org. Stores the derived rows only when `write` is set. */
473
577
  export async function orgObservedCommand(context, options = {}) {
474
578
  const org = await buildObservedOrg(context, options);
475
- const written = options.write === true ? writeObservedOrg(context, org) : null;
476
- const text = `${renderObserved(org)}\n\n${written ? `Stored ${written.rows} derived rows in ${written.dir}.` : "Nothing was stored. Pass --write to store the derived rows in the graph folder."}`;
477
- return { text, json: { ...org, stored: written } };
579
+ const roles = options.roles === true;
580
+ const written = options.write === true ? writeObservedOrg(context, org, { roles }) : null;
581
+ const text = `${renderObserved(org, { roles })}\n\n${written ? `Stored ${written.rows} derived rows in ${written.dir}.` : "Nothing was stored. Pass --write to store the derived rows in the graph folder."}`;
582
+ return { text, json: { ...(roles ? org : activityOnly(org)), stored: written } };
478
583
  }
479
584
  /** `hq ontology org compare`: stated versus observed. Writes nothing unless `write` is set. */
480
585
  export async function orgCompareCommand(context, options = {}) {
@@ -486,8 +591,9 @@ export async function orgCompareCommand(context, options = {}) {
486
591
  /** `hq ontology org person <name>`: one person. Writes nothing unless `write` is set. */
487
592
  export async function orgPersonCommand(context, options) {
488
593
  const org = await buildObservedOrg(context, options);
594
+ const roles = options.roles === true;
489
595
  if (options.write === true)
490
- writeObservedOrg(context, org);
596
+ writeObservedOrg(context, org, { roles });
491
597
  const wanted = normalizeName(options.name);
492
598
  const exact = org.people.filter((person) => normalizeName(person.name) === wanted || person.ref === options.name || person.ref === `person/${options.name}`);
493
599
  const loose = exact.length > 0 ? exact : org.people.filter((person) => normalizeName(person.name).split(" ").includes(wanted) || normalizeName(person.name).includes(wanted));
@@ -498,8 +604,19 @@ export async function orgPersonCommand(context, options) {
498
604
  return { text: `"${options.name}" matches ${loose.length} people: ${loose.map((person) => `${person.name} (${person.ref})`).join(", ")}. Name one.`, json: { meta: org.meta, matches: loose.map((person) => person.ref) }, exitCode: 1 };
499
605
  }
500
606
  const person = loose[0];
607
+ if (!roles) {
608
+ return {
609
+ text: renderPerson(org, person),
610
+ json: {
611
+ meta: org.meta,
612
+ person: activityOnly({ ...org, people: [person] }).people[0],
613
+ collaboration: org.collaboration.filter((edge) => edge.a === person.ref || edge.b === person.ref).slice(0, 10),
614
+ owns: activityOnly(org).owners.filter((owner) => owner.owner === person.ref),
615
+ },
616
+ };
617
+ }
501
618
  return {
502
- text: renderPerson(org, person),
619
+ text: renderPerson(org, person, { roles: true }),
503
620
  json: {
504
621
  meta: org.meta,
505
622
  person,
@@ -22,6 +22,8 @@ export interface NamedPerson {
22
22
  onRoster: boolean;
23
23
  }
24
24
  /** Finds people named in a line. Built once per graph. */
25
+ /** Labels a transcript uses when it does not know who spoke. Never a person. */
26
+ export declare const PLACEHOLDER_SPEAKERS: ReadonlySet<string>;
25
27
  export declare class NameIndex {
26
28
  private readonly entries;
27
29
  private readonly rosterFirst;
@@ -27,6 +27,8 @@ function escapeRegExp(text) {
27
27
  return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
28
28
  }
29
29
  /** Finds people named in a line. Built once per graph. */
30
+ /** Labels a transcript uses when it does not know who spoke. Never a person. */
31
+ export const PLACEHOLDER_SPEAKERS = new Set(["host", "speaker", "unknown", "participant", "guest", "attendee", "organizer", "presenter", "moderator"]);
30
32
  export class NameIndex {
31
33
  entries = new Map();
32
34
  rosterFirst = new Map();
@@ -69,6 +71,10 @@ export class NameIndex {
69
71
  const candidate = normalizeName(raw.replace(/(?:'s|’s)?[:,.]?$/, ""));
70
72
  if (candidate.length < 3)
71
73
  continue;
74
+ // A speaker label a transcript puts where a name should be is nobody, even when
75
+ // an entity carries it as an alias: the row is left unattributed.
76
+ if (take === 1 && PLACEHOLDER_SPEAKERS.has(candidate))
77
+ return null;
72
78
  const ref = this.match(candidate, filedOn);
73
79
  if (ref) {
74
80
  const consumed = new RegExp(`^(?:\\S+\\s+){${take - 1}}\\S+`).exec(stripped);