vindaris 0.0.0-stage → 0.1.0

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/src/model.js ADDED
@@ -0,0 +1,190 @@
1
+ // The Work Graph model as this package uses it: types, normalizing the JSON an
2
+ // agent writes, and validating it. Names follow github.com/Vindaris/work-graph-schema.
3
+
4
+ export const PLAN_TYPES = ['STRATEGY', 'GOAL', 'KPI', 'PROJECT', 'TASK'];
5
+ export const NODE_TYPES = [...PLAN_TYPES, 'PERSON', 'TEAM', 'MEETING'];
6
+ export const LINK_TYPES = ['CONTRIBUTES_TO', 'ALIGNED_TO', 'BLOCKED_BY', 'MEMBER_OF', 'LEADS', 'REPORTS_TO'];
7
+
8
+ // Height in the plan. A CONTRIBUTES_TO link points from lower to higher.
9
+ export const RANK = { TASK: 1, PROJECT: 2, KPI: 3, GOAL: 4, STRATEGY: 5 };
10
+
11
+ // Shorthand collections an agent may write instead of a flat `nodes` list.
12
+ const COLLECTIONS = {
13
+ strategies: 'STRATEGY', strategy: 'STRATEGY',
14
+ goals: 'GOAL', okrs: 'GOAL', objectives: 'GOAL',
15
+ kpis: 'KPI', keyResults: 'KPI', key_results: 'KPI', metrics: 'KPI',
16
+ projects: 'PROJECT', initiatives: 'PROJECT', epics: 'PROJECT',
17
+ tasks: 'TASK', issues: 'TASK', work: 'TASK',
18
+ people: 'PERSON', persons: 'PERSON',
19
+ teams: 'TEAM',
20
+ meetings: 'MEETING',
21
+ };
22
+
23
+ export function slug(s) {
24
+ return String(s).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '')
25
+ .replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 40) || 'x';
26
+ }
27
+
28
+ export function emptyGraph() {
29
+ return { version: 1, meta: { sources: [] }, nodes: [], edges: [] };
30
+ }
31
+
32
+ /**
33
+ * Turn whatever shape the agent wrote into { nodes, edges, meta } in schema form.
34
+ * Returns { batch, problems } where problems are strings to show the agent.
35
+ */
36
+ export function normalizeInput(input) {
37
+ const problems = [];
38
+ const nodes = [];
39
+ const edges = [];
40
+ const meta = { sources: [] };
41
+ const people = new Map(); // name slug -> person node, for owner/assignee given by name
42
+
43
+ const personRef = (val) => {
44
+ if (val == null || val === '') return null;
45
+ const s = String(val).trim();
46
+ if (/^per_/.test(s)) return s;
47
+ const id = 'per_' + slug(s);
48
+ if (!people.has(id)) people.set(id, { id, type: 'PERSON', name: s });
49
+ return id;
50
+ };
51
+
52
+ if (input == null || typeof input !== 'object') {
53
+ return { batch: { nodes, edges, meta }, problems: ['Input is not a JSON object or array.'] };
54
+ }
55
+ if (Array.isArray(input)) input = { nodes: input };
56
+
57
+ const rawNodes = [];
58
+ for (const n of input.nodes || []) rawNodes.push([n, null]);
59
+ for (const [key, type] of Object.entries(COLLECTIONS)) {
60
+ if (Array.isArray(input[key])) for (const n of input[key]) rawNodes.push([n, type]);
61
+ }
62
+
63
+ for (const [raw, impliedType] of rawNodes) {
64
+ if (!raw || typeof raw !== 'object') { problems.push('Skipped a node that is not an object.'); continue; }
65
+ const n = { ...raw };
66
+ n.type = String(n.type || impliedType || '').toUpperCase();
67
+ if (n.type === 'OBJECTIVE' || n.type === 'OKR') n.type = 'GOAL';
68
+ if (n.type === 'KEY_RESULT' || n.type === 'METRIC') n.type = 'KPI';
69
+ if (n.type === 'ISSUE' || n.type === 'TICKET') n.type = 'TASK';
70
+ if (n.type === 'EPIC' || n.type === 'INITIATIVE') n.type = 'PROJECT';
71
+ if (!NODE_TYPES.includes(n.type)) { problems.push(`Skipped node ${JSON.stringify(raw.id || raw.title || raw.name)}: unknown type "${raw.type || impliedType}".`); continue; }
72
+ if (n.type === 'PERSON' || n.type === 'TEAM') {
73
+ n.name = n.name || n.title;
74
+ if (!n.name) { problems.push(`Skipped a ${n.type} without a name.`); continue; }
75
+ n.id = n.id || (n.type === 'PERSON' ? 'per_' : 'team_') + slug(n.name);
76
+ delete n.title;
77
+ } else {
78
+ n.title = n.title || n.name || n.key;
79
+ if (!n.title) { problems.push(`Skipped a ${n.type} without a title.`); continue; }
80
+ n.id = String(n.id || n.key || `${n.type.toLowerCase()}_${slug(n.title)}`);
81
+ delete n.name;
82
+ }
83
+ // Owner and assignee may be given by name.
84
+ if (n.owner !== undefined && n.ownerId === undefined) n.ownerId = personRef(n.owner);
85
+ if (n.assignee !== undefined && n.assigneeId === undefined) n.assigneeId = personRef(n.assignee);
86
+ delete n.owner; delete n.assignee;
87
+ if (n.ownerId && !/^per_/.test(n.ownerId)) n.ownerId = personRef(n.ownerId);
88
+ if (n.assigneeId && !/^per_/.test(n.assigneeId)) n.assigneeId = personRef(n.assigneeId);
89
+ if (n.type === 'TASK' && !n.status) n.status = n.completedAt ? 'Done' : 'Unknown';
90
+ if (typeof n.container === 'string') n.container = { key: n.container, name: n.container };
91
+ for (const k of ['startValue', 'currentValue', 'targetValue', 'progress']) {
92
+ if (typeof n[k] === 'string' && n[k].trim() !== '' && !isNaN(Number(n[k].replace(/[, %€$]/g, '')))) n[k] = Number(n[k].replace(/[, %€$]/g, ''));
93
+ }
94
+ // Inline parent links: { parent: "goal_1" } or { goal: "goal_1" } or { contributesTo: [...] }.
95
+ const parents = [].concat(n.parent ?? [], n.parents ?? [], n.goal ?? [], n.contributesTo ?? []);
96
+ for (const p of parents) {
97
+ if (p && typeof p === 'object') edges.push({ type: 'CONTRIBUTES_TO', from: n.id, to: p.id, confidence: p.confidence, origin: p.origin });
98
+ else if (p) edges.push({ type: 'CONTRIBUTES_TO', from: n.id, to: String(p), confidence: n.linkConfidence, origin: n.linkOrigin });
99
+ }
100
+ delete n.parent; delete n.parents; delete n.goal; delete n.contributesTo; delete n.linkConfidence; delete n.linkOrigin;
101
+ nodes.push(n);
102
+ }
103
+ for (const p of people.values()) nodes.push(p);
104
+
105
+ for (const raw of [...(input.edges || []), ...(input.links || [])]) {
106
+ if (!raw || typeof raw !== 'object') { problems.push('Skipped a link that is not an object.'); continue; }
107
+ edges.push({ ...raw });
108
+ }
109
+
110
+ if (input.meta && typeof input.meta === 'object') {
111
+ if (Array.isArray(input.meta.sources)) meta.sources.push(...input.meta.sources);
112
+ if (input.meta.company) meta.company = String(input.meta.company);
113
+ if (input.meta.period) meta.period = input.meta.period;
114
+ }
115
+ if (Array.isArray(input.sources)) meta.sources.push(...input.sources);
116
+ if (input.company) meta.company = String(input.company);
117
+
118
+ return { batch: { nodes, edges, meta }, problems };
119
+ }
120
+
121
+ /** Resolve link shorthand ({from, to}) against the known nodes into schema edges. */
122
+ export function resolveEdges(rawEdges, nodeIndex) {
123
+ const edges = [];
124
+ const problems = [];
125
+ for (const e of rawEdges) {
126
+ const srcId = e.source?.id ?? e.from ?? e.source;
127
+ const tgtId = e.target?.id ?? e.to ?? e.target;
128
+ const src = nodeIndex.get(String(srcId));
129
+ const tgt = nodeIndex.get(String(tgtId));
130
+ if (!src || !tgt) {
131
+ problems.push(`Link ${srcId} -> ${tgtId}: ${!src ? `"${srcId}"` : `"${tgtId}"`} is not in the graph yet. Add the node, then add the link again.`);
132
+ continue;
133
+ }
134
+ let type = String(e.type || '').toUpperCase();
135
+ if (!type) {
136
+ if (src.type === 'PERSON' && tgt.type === 'TEAM') type = 'MEMBER_OF';
137
+ else if (src.type === 'PERSON' && tgt.type === 'PERSON') type = 'REPORTS_TO';
138
+ else type = 'CONTRIBUTES_TO';
139
+ }
140
+ if (!LINK_TYPES.includes(type)) { problems.push(`Link ${srcId} -> ${tgtId}: unknown link type "${e.type}".`); continue; }
141
+ if (type === 'CONTRIBUTES_TO' && RANK[src.type] && RANK[tgt.type] && RANK[src.type] > RANK[tgt.type]) {
142
+ problems.push(`Link ${srcId} -> ${tgtId}: CONTRIBUTES_TO points upward (task to project to KPI to goal to strategy). Swap from and to.`);
143
+ continue;
144
+ }
145
+ let confidence = e.confidence == null ? null : Number(e.confidence);
146
+ if (confidence != null && (isNaN(confidence) || confidence < 0 || confidence > 1)) {
147
+ problems.push(`Link ${srcId} -> ${tgtId}: confidence must be between 0 and 1. Kept the link without one.`);
148
+ confidence = null;
149
+ }
150
+ const origin = e.origin ? String(e.origin).toUpperCase() : (confidence == null ? 'HUMAN' : 'AUTO');
151
+ const edge = { type, source: { type: src.type, id: src.id }, target: { type: tgt.type, id: tgt.id }, origin };
152
+ if (origin === 'AUTO') edge.confidence = confidence ?? 0.5;
153
+ if (e.reason) edge.reason = String(e.reason).slice(0, 300);
154
+ if (e.weight != null) edge.weight = Number(e.weight);
155
+ edges.push(edge);
156
+ }
157
+ return { edges, problems };
158
+ }
159
+
160
+ export const edgeKey = (e) => `${e.type}|${e.source.id}|${e.target.id}`;
161
+
162
+ /** Merge a normalized batch into the stored graph. Later values win per id. */
163
+ export function mergeBatch(graph, batch) {
164
+ const problems = [];
165
+ const index = new Map(graph.nodes.map((n) => [n.id, n]));
166
+ let added = 0, updated = 0;
167
+ for (const n of batch.nodes) {
168
+ const prev = index.get(n.id);
169
+ if (prev && prev.type !== n.type) {
170
+ problems.push(`Node "${n.id}" exists as ${prev.type}; skipped the ${n.type} with the same id. Use a different id.`);
171
+ continue;
172
+ }
173
+ if (prev) { Object.assign(prev, n); updated++; } else { const copy = { ...n }; graph.nodes.push(copy); index.set(n.id, copy); added++; }
174
+ }
175
+ const { edges, problems: edgeProblems } = resolveEdges(batch.edges, index);
176
+ problems.push(...edgeProblems);
177
+ const known = new Map(graph.edges.map((e) => [edgeKey(e), e]));
178
+ let linksAdded = 0;
179
+ for (const e of edges) {
180
+ const k = edgeKey(e);
181
+ if (known.has(k)) Object.assign(known.get(k), e);
182
+ else { graph.edges.push(e); known.set(k, e); linksAdded++; }
183
+ }
184
+ for (const s of batch.meta.sources) {
185
+ if (!graph.meta.sources.some((x) => JSON.stringify(x) === JSON.stringify(s))) graph.meta.sources.push(s);
186
+ }
187
+ if (batch.meta.company) graph.meta.company = batch.meta.company;
188
+ if (batch.meta.period) graph.meta.period = batch.meta.period;
189
+ return { added, updated, linksAdded, problems };
190
+ }