eyeling 1.16.3 → 1.16.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.
Files changed (45) hide show
  1. package/README.md +0 -1
  2. package/package.json +2 -3
  3. package/arctifacts/README.md +0 -59
  4. package/arctifacts/ackermann.html +0 -678
  5. package/arctifacts/auroracare.html +0 -1297
  6. package/arctifacts/bike-trip.html +0 -752
  7. package/arctifacts/binomial-theorem.html +0 -631
  8. package/arctifacts/bmi.html +0 -511
  9. package/arctifacts/building-performance.html +0 -750
  10. package/arctifacts/clinical-care.html +0 -726
  11. package/arctifacts/collatz.html +0 -403
  12. package/arctifacts/complex.html +0 -321
  13. package/arctifacts/control-system.html +0 -482
  14. package/arctifacts/delfour.html +0 -849
  15. package/arctifacts/earthquake-epicenter.html +0 -982
  16. package/arctifacts/eco-route.html +0 -662
  17. package/arctifacts/euclid-infinitude.html +0 -564
  18. package/arctifacts/euler-identity.html +0 -667
  19. package/arctifacts/exoplanet-transit.html +0 -1000
  20. package/arctifacts/faltings-theorem.html +0 -1046
  21. package/arctifacts/fibonacci.html +0 -299
  22. package/arctifacts/fundamental-theorem-arithmetic.html +0 -398
  23. package/arctifacts/godel-numbering.html +0 -743
  24. package/arctifacts/gps-bike.html +0 -759
  25. package/arctifacts/gps-clinical-bench.html +0 -792
  26. package/arctifacts/graph-french.html +0 -449
  27. package/arctifacts/grass-molecular.html +0 -592
  28. package/arctifacts/group-theory.html +0 -740
  29. package/arctifacts/health-info.html +0 -833
  30. package/arctifacts/kaprekar-constant.html +0 -576
  31. package/arctifacts/lee.html +0 -805
  32. package/arctifacts/linked-lists.html +0 -502
  33. package/arctifacts/lldm.html +0 -612
  34. package/arctifacts/matrix-multiplication.html +0 -502
  35. package/arctifacts/matrix.html +0 -651
  36. package/arctifacts/newton-raphson.html +0 -944
  37. package/arctifacts/peano-factorial.html +0 -456
  38. package/arctifacts/pi.html +0 -363
  39. package/arctifacts/polynomial.html +0 -646
  40. package/arctifacts/prime.html +0 -366
  41. package/arctifacts/pythagorean-theorem.html +0 -468
  42. package/arctifacts/rest-path.html +0 -469
  43. package/arctifacts/roots-of-unity.html +0 -363
  44. package/arctifacts/turing.html +0 -409
  45. package/arctifacts/wind-turbines.html +0 -726
@@ -1,726 +0,0 @@
1
- <!doctype html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width, initial-scale=1" />
6
- <title>Clinical Care Planning</title>
7
- <style>
8
- :root {
9
- --bg: #f7f9fc;
10
- --card: #ffffff;
11
- --muted: #5b6b87;
12
- --text: #0f172a;
13
- --accent: #0ea5e9;
14
- --ok: #16a34a;
15
- --bad: #dc2626;
16
- --border: #e5e7eb;
17
- }
18
- html,
19
- body {
20
- height: 100%;
21
- background: var(--bg);
22
- color: var(--text);
23
- font:
24
- 15px/1.5 system-ui,
25
- -apple-system,
26
- Segoe UI,
27
- Roboto,
28
- Inter,
29
- Helvetica,
30
- Arial,
31
- sans-serif;
32
- }
33
- h1 {
34
- font-weight: 700;
35
- letter-spacing: 0.2px;
36
- margin: 18px 0 6px;
37
- }
38
- h2 {
39
- font-size: 13px;
40
- color: var(--muted);
41
- margin: 0 0 8px;
42
- letter-spacing: 0.2px;
43
- text-transform: uppercase;
44
- }
45
- .wrap {
46
- max-width: 980px;
47
- margin: 0 auto;
48
- padding: 24px;
49
- }
50
- .stack {
51
- display: grid;
52
- grid-template-columns: 1fr;
53
- gap: 14px;
54
- }
55
- .card {
56
- background: var(--card);
57
- border: 1px solid var(--border);
58
- border-radius: 14px;
59
- padding: 14px;
60
- box-shadow: 0 6px 20px rgba(0, 0, 0, 0.04);
61
- }
62
- .row {
63
- display: flex;
64
- gap: 10px;
65
- align-items: center;
66
- flex-wrap: wrap;
67
- }
68
- button {
69
- border: 0;
70
- background: linear-gradient(180deg, #7dd3fc, #38bdf8);
71
- color: #052436;
72
- padding: 10px 14px;
73
- border-radius: 12px;
74
- font-weight: 700;
75
- cursor: pointer;
76
- box-shadow: 0 3px 12px rgba(56, 189, 248, 0.35);
77
- }
78
- button.secondary {
79
- background: #f3f4f6;
80
- color: #111827;
81
- border: 1px solid var(--border);
82
- box-shadow: none;
83
- }
84
- .output {
85
- min-height: 0;
86
- white-space: pre-wrap;
87
- background: #fbfdff;
88
- border: 1px solid var(--border);
89
- border-radius: 10px;
90
- padding: 10px;
91
- overflow: auto;
92
- }
93
- .output.tall {
94
- min-height: 160px;
95
- }
96
- .muted {
97
- color: var(--muted);
98
- }
99
- .badge {
100
- display: inline-block;
101
- padding: 2px 8px;
102
- border-radius: 999px;
103
- font-size: 12px;
104
- font-weight: 700;
105
- letter-spacing: 0.3px;
106
- border: 1px solid var(--border);
107
- }
108
- .ok {
109
- background: rgba(22, 163, 74, 0.08);
110
- color: var(--ok);
111
- border-color: rgba(22, 163, 74, 0.35);
112
- }
113
- .bad {
114
- background: rgba(220, 38, 38, 0.08);
115
- color: var(--bad);
116
- border-color: rgba(220, 38, 38, 0.35);
117
- }
118
- .tiny {
119
- font-size: 12px;
120
- }
121
- .diag {
122
- font-size: 12px;
123
- color: #6b7280;
124
- }
125
- textarea,
126
- pre,
127
- code,
128
- input,
129
- button {
130
- font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, 'Courier New', monospace;
131
- }
132
- textarea {
133
- width: 100%;
134
- min-height: 0;
135
- height: auto;
136
- overflow: hidden;
137
- resize: none;
138
- border-radius: 10px;
139
- padding: 10px;
140
- border: 1px solid var(--border);
141
- background: #fbfdff;
142
- color: #var(--text);
143
- box-sizing: border-box;
144
- white-space: pre-wrap;
145
- }
146
- </style>
147
- </head>
148
- <body>
149
- <div class="wrap">
150
- <h1>Clinical Care Planning</h1>
151
-
152
- <div class="stack">
153
- <!-- What this is? -->
154
- <div class="card" id="what">
155
- <h2>What this is?</h2>
156
- <p>
157
- One-file, pure JS + JSON clinical reasoning demo using ARC: <strong>Answer</strong> •
158
- <strong>Reason</strong> • <strong>Check</strong>.
159
- </p>
160
- <ul>
161
- <li><strong>Data</strong> — JSON patients, body parts, observations.</li>
162
- <li>
163
- <strong>Policies</strong> — declarative JSON rules (<code>if</code> atoms, optional
164
- <code>"not": true</code> negations ⇒ <code>then</code> atoms).
165
- </li>
166
- <li><strong>Answer</strong> — only <em>newly derived</em> facts (keeps strongest priority per patient).</li>
167
- <li><strong>Reason Why</strong> — mathematical-English templates with variable bindings.</li>
168
- <li><strong>Check</strong> — ≥10 JSON assertions against the full fact set.</li>
169
- <li>
170
- <strong>Care Plan Summary</strong> — per-patient priority & planned interventions (chooses strongest
171
- priority).
172
- </li>
173
- </ul>
174
- <p class="tiny muted">
175
- Engine: small forward-chainer with unification, subclassing (<code>subClass</code>), transitive
176
- <code>partOf</code>, observation → patient mapping, and negation-as-failure for <code>"not": true</code>.
177
- </p>
178
- </div>
179
-
180
- <div class="card">
181
- <h2>Data (JSON)</h2>
182
- <textarea id="dataTA" spellcheck="false">
183
- {
184
- "classes": ["Patient","BodyPart",
185
- "Observation","RedFlag","MajorConcern","MinorConcern",
186
- "ChestPain","Hypoxia","Fever","Cough","Wheeze","HighBP","Headache","SoreThroat",
187
- "CarePriority","Emergency","High","Routine","CareTask","RequiresImmediateCare"],
188
-
189
- "subclassOf": [
190
- ["ChestPain","RedFlag"],
191
- ["Hypoxia","RedFlag"],
192
- ["Fever","MajorConcern"],
193
- ["Cough","MinorConcern"],
194
- ["Wheeze","MinorConcern"],
195
- ["HighBP","MinorConcern"],
196
- ["Headache","MinorConcern"],
197
- ["RedFlag","Observation"],
198
- ["MajorConcern","Observation"],
199
- ["MinorConcern","Observation"]
200
- ],
201
-
202
- "assets": {
203
- "P1": {"type":"Patient"},
204
- "Heart1": {"type":"BodyPart","partOf":"P1"},
205
- "Lung1": {"type":"BodyPart","partOf":"P1"},
206
-
207
- "P2": {"type":"Patient"},
208
- "Lung2": {"type":"BodyPart","partOf":"P2"},
209
-
210
- "P3": {"type":"Patient"}
211
- },
212
-
213
- "observations": [
214
- {"id":"ObsCP1","type":"ChestPain","about":"Heart1"},
215
- {"id":"ObsO2P1","type":"Hypoxia","about":"Lung1"},
216
- {"id":"ObsFeverP1","type":"Fever","about":"P1"},
217
-
218
- {"id":"ObsCoughP2","type":"Cough","about":"P2"},
219
- {"id":"ObsWheezeP2","type":"Wheeze","about":"P2"},
220
- {"id":"ObsFeverP2","type":"Fever","about":"P2"},
221
-
222
- {"id":"ObsBP3","type":"HighBP","about":"P3"},
223
- {"id":"ObsHeadache3","type":"Headache","about":"P3"}
224
- ]
225
- }</textarea
226
- >
227
- </div>
228
-
229
- <div class="card">
230
- <h2>Policies (declarative JSON rules)</h2>
231
- <textarea id="policyTA" spellcheck="false">
232
- [
233
- {
234
- "id": "R1-Subclass",
235
- "if": [ {"pred":"subClass","s":"?A","o":"?B"}, {"pred":"isA","s":"?S","o":"?A"} ],
236
- "then":[ {"pred":"isA","s":"?S","o":"?B"} ],
237
- "explain": "Since ?A ⊑ ?B and ?S ∈ ?A, infer ?S ∈ ?B."
238
- },
239
- {
240
- "id": "R2-PartOfTransitive",
241
- "if": [ {"pred":"partOf","s":"?x","o":"?y"}, {"pred":"partOf","s":"?y","o":"?z"} ],
242
- "then":[ {"pred":"partOf","s":"?x","o":"?z"} ],
243
- "explain": "Because ?x is part of ?y and ?y is part of ?z, by transitivity ?x is part of ?z."
244
- },
245
- {
246
- "id": "R3-ObsToPatient",
247
- "if": [ {"pred":"about","s":"?obs","o":"?part"}, {"pred":"partOf","s":"?part","o":"?P"} ],
248
- "then":[ {"pred":"aboutPatient","s":"?obs","o":"?P"} ],
249
- "explain": "Observation ?obs concerns body part ?part of patient ?P; therefore ?obs is about patient ?P."
250
- },
251
-
252
- {
253
- "id": "T-ChestPain",
254
- "if": [ {"pred":"isA","s":"?obs","o":"ChestPain"}, {"pred":"aboutPatient","s":"?obs","o":"?P"} ],
255
- "then":[ {"pred":"requiresTask","s":"?P","o":"EKG"},
256
- {"pred":"requiresTask","s":"?P","o":"TroponinLab"} ],
257
- "explain": "Chest pain in ?P implies EKG and troponin testing."
258
- },
259
- {
260
- "id": "T-Hypoxia",
261
- "if": [ {"pred":"isA","s":"?obs","o":"Hypoxia"}, {"pred":"aboutPatient","s":"?obs","o":"?P"} ],
262
- "then":[ {"pred":"requiresTask","s":"?P","o":"OxygenTherapy"},
263
- {"pred":"requiresTask","s":"?P","o":"ChestXRay"} ],
264
- "explain": "Hypoxia in ?P implies oxygen therapy and chest radiography."
265
- },
266
- {
267
- "id": "T-Fever",
268
- "if": [ {"pred":"isA","s":"?obs","o":"Fever"}, {"pred":"aboutPatient","s":"?obs","o":"?P"} ],
269
- "then":[ {"pred":"requiresTask","s":"?P","o":"Antipyretic"},
270
- {"pred":"requiresTask","s":"?P","o":"RepeatVitals"} ],
271
- "explain": "Fever in ?P implies antipyretic treatment and repeat vitals."
272
- },
273
- {
274
- "id": "T-Fever+Cough→COVIDTest",
275
- "if": [ {"pred":"isA","s":"?o1","o":"Fever"}, {"pred":"aboutPatient","s":"?o1","o":"?P"},
276
- {"pred":"isA","s":"?o2","o":"Cough"}, {"pred":"aboutPatient","s":"?o2","o":"?P"} ],
277
- "then":[ {"pred":"requiresTask","s":"?P","o":"COVIDTest"} ],
278
- "explain": "Fever and cough in the same patient ?P suggest COVID testing."
279
- },
280
- {
281
- "id": "T-Wheeze",
282
- "if": [ {"pred":"isA","s":"?obs","o":"Wheeze"}, {"pred":"aboutPatient","s":"?obs","o":"?P"} ],
283
- "then":[ {"pred":"requiresTask","s":"?P","o":"Nebulizer"} ],
284
- "explain": "Wheezing in ?P suggests bronchodilator (nebulizer) therapy."
285
- },
286
- {
287
- "id": "T-HighBP",
288
- "if": [ {"pred":"isA","s":"?obs","o":"HighBP"}, {"pred":"aboutPatient","s":"?obs","o":"?P"} ],
289
- "then":[ {"pred":"requiresTask","s":"?P","o":"BPRecheck"},
290
- {"pred":"requiresTask","s":"?P","o":"Hydration"} ],
291
- "explain": "Isolated high BP in ?P suggests BP recheck and hydration."
292
- },
293
-
294
- {
295
- "id": "P-RedFlag→Emergency",
296
- "if": [ {"pred":"isA","s":"?obs","o":"RedFlag"}, {"pred":"aboutPatient","s":"?obs","o":"?P"} ],
297
- "then":[ {"pred":"isA","s":"?P","o":"RequiresImmediateCare"},
298
- {"pred":"priority","s":"?P","o":"Emergency"} ],
299
- "explain": "Any red flag for ?P warrants immediate care and Emergency priority."
300
- },
301
- {
302
- "id": "P-Major-NotRedFlag→High",
303
- "if": [ {"pred":"isA","s":"?obs","o":"MajorConcern"}, {"pred":"aboutPatient","s":"?obs","o":"?P"},
304
- {"not":true, "pred":"isA","s":"?obs","o":"RedFlag"} ],
305
- "then":[ {"pred":"priority","s":"?P","o":"High"} ],
306
- "explain": "A major (but not red-flag) concern for ?P implies High priority."
307
- },
308
- {
309
- "id": "P-Default-Routine",
310
- "if": [ {"pred":"requiresTask","s":"?P","o":"?X"},
311
- {"not":true, "pred":"priority","s":"?P","o":"?Any"} ],
312
- "then":[ {"pred":"priority","s":"?P","o":"Routine"} ],
313
- "explain": "If ?P has a care task and no assigned priority, default to Routine."
314
- }
315
- ]</textarea
316
- >
317
- </div>
318
-
319
- <div class="card">
320
- <h2>Checks (JSON)</h2>
321
- <textarea id="checksTA" spellcheck="false">
322
- [
323
- {"name":"ObsCP1 is about patient P1", "pattern":{"pred":"aboutPatient","s":"ObsCP1","o":"P1"}},
324
- {"name":"ObsO2P1 is about patient P1", "pattern":{"pred":"aboutPatient","s":"ObsO2P1","o":"P1"}},
325
- {"name":"ObsFeverP1 is about patient P1", "pattern":{"pred":"aboutPatient","s":"ObsFeverP1","o":"P1"}},
326
- {"name":"ObsCoughP2 is about patient P2", "pattern":{"pred":"aboutPatient","s":"ObsCoughP2","o":"P2"}},
327
- {"name":"ObsWheezeP2 is about patient P2", "pattern":{"pred":"aboutPatient","s":"ObsWheezeP2","o":"P2"}},
328
-
329
- {"name":"P1 requires EKG", "pattern":{"pred":"requiresTask","s":"P1","o":"EKG"}},
330
- {"name":"P1 requires TroponinLab", "pattern":{"pred":"requiresTask","s":"P1","o":"TroponinLab"}},
331
- {"name":"P1 requires OxygenTherapy", "pattern":{"pred":"requiresTask","s":"P1","o":"OxygenTherapy"}},
332
- {"name":"P1 requires ChestXRay", "pattern":{"pred":"requiresTask","s":"P1","o":"ChestXRay"}},
333
- {"name":"P1 requires Antipyretic", "pattern":{"pred":"requiresTask","s":"P1","o":"Antipyretic"}},
334
-
335
- {"name":"P1 Emergency priority", "pattern":{"pred":"priority","s":"P1","o":"Emergency"}},
336
- {"name":"P2 High priority", "pattern":{"pred":"priority","s":"P2","o":"High"}},
337
- {"name":"P3 Routine priority", "pattern":{"pred":"priority","s":"P3","o":"Routine"}},
338
-
339
- {"name":"P2 requires COVIDTest", "pattern":{"pred":"requiresTask","s":"P2","o":"COVIDTest"}},
340
- {"name":"P2 requires Nebulizer", "pattern":{"pred":"requiresTask","s":"P2","o":"Nebulizer"}},
341
- {"name":"P2 requires Antipyretic", "pattern":{"pred":"requiresTask","s":"P2","o":"Antipyretic"}},
342
-
343
- {"name":"P3 requires BPRecheck", "pattern":{"pred":"requiresTask","s":"P3","o":"BPRecheck"}}
344
- ]</textarea
345
- >
346
- </div>
347
-
348
- <div class="card">
349
- <h2>Controls</h2>
350
- <div class="row">
351
- <button id="runBtn">▶ Run ARC</button>
352
- <button id="reasonBtn" class="secondary">Show Reason only</button>
353
- <span id="status" class="muted tiny" style="margin-left: auto"></span>
354
- </div>
355
- <div id="diag" class="diag"></div>
356
- </div>
357
-
358
- <div class="card">
359
- <h2>Answer (newly derived facts)</h2>
360
- <div id="answer" class="output tall">computing…</div>
361
- </div>
362
-
363
- <div class="card">
364
- <h2>Reason Why (mathematical English)</h2>
365
- <div id="reason" class="output tall">(click “Run ARC”)</div>
366
- </div>
367
-
368
- <div class="card">
369
- <h2>Check</h2>
370
- <div id="checks" class="output tall">computing…</div>
371
- </div>
372
-
373
- <div class="card">
374
- <h2>Care Plan Summary</h2>
375
- <div id="summary" class="output">(run to populate)</div>
376
- </div>
377
- </div>
378
- </div>
379
-
380
- <script>
381
- const $ = (id) => document.getElementById(id);
382
- const els = {
383
- dataTA: $('dataTA'),
384
- policyTA: $('policyTA'),
385
- checksTA: $('checksTA'),
386
- runBtn: $('runBtn'),
387
- reasonBtn: $('reasonBtn'),
388
- status: $('status'),
389
- diag: $('diag'),
390
- answer: $('answer'),
391
- reason: $('reason'),
392
- checks: $('checks'),
393
- summary: $('summary'),
394
- };
395
-
396
- // Auto-grow textareas
397
- function autoResize(el) {
398
- el.style.height = 'auto';
399
- el.style.height = el.scrollHeight + 'px';
400
- }
401
- ['dataTA', 'policyTA', 'checksTA'].forEach((id) => {
402
- const el = $(id);
403
- el.addEventListener('input', () => autoResize(el));
404
- setTimeout(() => autoResize(el), 0);
405
- });
406
-
407
- // ---- Tiny fact KB
408
- function key(f) {
409
- return `${f.pred}|${f.s}|${f.o}`;
410
- }
411
-
412
- function buildFactsFromData(data) {
413
- const facts = [];
414
- (data.subclassOf || []).forEach(([a, b]) => facts.push({ pred: 'subClass', s: a, o: b, _base: true }));
415
- for (const [id, info] of Object.entries(data.assets || {})) {
416
- if (info.type) facts.push({ pred: 'isA', s: id, o: info.type, _base: true });
417
- if (info.partOf) facts.push({ pred: 'partOf', s: id, o: info.partOf, _base: true });
418
- }
419
- (data.observations || []).forEach((o) => {
420
- facts.push({ pred: 'isA', s: o.id, o: o.type, _base: true });
421
- facts.push({ pred: 'about', s: o.id, o: o.about, _base: true });
422
- if (data.assets[o.about]?.type === 'Patient') {
423
- facts.push({ pred: 'aboutPatient', s: o.id, o: o.about, _base: true });
424
- }
425
- });
426
- return facts;
427
- }
428
-
429
- function indexFacts(facts) {
430
- const byPred = new Map();
431
- for (const f of facts) {
432
- if (!byPred.has(f.pred)) byPred.set(f.pred, []);
433
- byPred.get(f.pred).push(f);
434
- }
435
- return { byPred };
436
- }
437
-
438
- function isVar(x) {
439
- return typeof x === 'string' && x.startsWith('?');
440
- }
441
-
442
- function unifyAtomWithFact(atom, f, env) {
443
- const out = { ...env };
444
- const slots = ['pred', 's', 'o'];
445
- for (const slot of slots) {
446
- const val = atom[slot];
447
- const factVal = f[slot] ?? (slot === 'pred' ? f.pred : slot === 's' ? f.s : f.o);
448
- if (isVar(val)) {
449
- if (out[val] !== undefined && out[val] !== factVal) return null;
450
- out[val] = factVal;
451
- } else {
452
- if (val !== factVal) return null;
453
- }
454
- }
455
- return out;
456
- }
457
-
458
- function matchPositives(rule, factsIdx, env = {}, i = 0) {
459
- if (i >= rule.if.length) return [env];
460
- const atom = rule.if[i];
461
- if (atom.not) return matchPositives(rule, factsIdx, env, i + 1);
462
- const candidates = factsIdx.byPred.get(atom.pred) || [];
463
- const out = [];
464
- for (const f of candidates) {
465
- const env2 = unifyAtomWithFact(atom, f, env);
466
- if (env2) out.push(...matchPositives(rule, factsIdx, env2, i + 1));
467
- }
468
- return out;
469
- }
470
-
471
- function negHolds(atom, factsIdx, env) {
472
- const candidates = factsIdx.byPred.get(atom.pred) || [];
473
- for (const f of candidates) {
474
- if (unifyAtomWithFact(atom, f, env)) return true;
475
- }
476
- return false;
477
- }
478
-
479
- function substitute(t, env) {
480
- const sub = (v) => (isVar(v) ? env[v] : v);
481
- return { pred: t.pred, s: sub(t.s), o: sub(t.o) };
482
- }
483
-
484
- // ---- Priority handling
485
- const PRIORITY_RANK = { Emergency: 3, High: 2, Routine: 1 };
486
-
487
- function bestPriorities(facts) {
488
- const best = new Map();
489
- for (const f of facts) {
490
- if (f.pred !== 'priority') continue;
491
- const cur = best.get(f.s);
492
- if (!cur || (PRIORITY_RANK[f.o] || 0) > (PRIORITY_RANK[cur] || 0)) {
493
- best.set(f.s, f.o);
494
- }
495
- }
496
- return best;
497
- }
498
-
499
- function derive(data, policies) {
500
- let facts = buildFactsFromData(data);
501
- const baseSet = new Set(facts.map(key));
502
- const factSet = new Set(baseSet);
503
- const factsIdx = indexFacts(facts);
504
- const proofs = new Map();
505
-
506
- let changed = true,
507
- guard = 0;
508
- while (changed && guard++ < 200) {
509
- changed = false;
510
- for (const rule of policies) {
511
- const posBindings = matchPositives(rule, factsIdx, {}, 0);
512
- for (const env of posBindings) {
513
- const negs = rule.if.filter((a) => a.not);
514
- let ok = true,
515
- negUsed = [];
516
- for (const n of negs) {
517
- const nSub = substitute(n, env);
518
- if (negHolds(nSub, factsIdx, env)) {
519
- ok = false;
520
- break;
521
- }
522
- negUsed.push(nSub);
523
- }
524
- if (!ok) continue;
525
-
526
- for (const t of rule.then) {
527
- const concl = substitute(t, env);
528
- const k = key(concl);
529
- if (!factSet.has(k)) {
530
- facts.push({ ...concl, _base: false });
531
- factSet.add(k);
532
- changed = true;
533
- if (!factsIdx.byPred.has(concl.pred)) factsIdx.byPred.set(concl.pred, []);
534
- factsIdx.byPred.get(concl.pred).push({ ...concl, _base: false });
535
- const exp = buildExplanation(rule, env, negUsed);
536
- proofs.set(k, exp);
537
- }
538
- }
539
- }
540
- }
541
- }
542
-
543
- const derived = facts.filter((f) => !f._base);
544
-
545
- // Keep only strongest priority per patient for Answer/Reason
546
- const best = bestPriorities(facts);
547
- const derivedFiltered = derived.filter((f) => f.pred !== 'priority' || best.get(f.s) === f.o);
548
-
549
- const answerLines = formatFacts(derivedFiltered);
550
-
551
- const reasonLines = [];
552
- for (const f of derivedFiltered) {
553
- const k = key(f);
554
- const exp = proofs.get(k);
555
- if (exp) reasonLines.push(`• ${exp} ⇒ therefore ${prettyFact(f)}.`);
556
- else reasonLines.push(`• Derived ${prettyFact(f)}.`);
557
- }
558
-
559
- return { facts, derived, answerText: answerLines.join('\n'), reasonText: reasonLines.join('\n') };
560
- }
561
-
562
- function buildExplanation(rule, env, negUsed) {
563
- const fill = (s) => s.replace(/\?[A-Za-z0-9_]+/g, (m) => env[m] ?? m);
564
- let text = fill(rule.explain || `Applied ${rule.id}`);
565
- if (negUsed && negUsed.length) {
566
- const negBits = negUsed.map((n) => `no fact ${n.pred}(${n.s}, ${n.o})`).join(' and ');
567
- text += `, and ${negBits}`;
568
- }
569
- return text;
570
- }
571
-
572
- function prettyFact(f) {
573
- const p = f.pred,
574
- s = f.s,
575
- o = f.o;
576
- const tri = {
577
- isA: `${s} ∈ ${o}`,
578
- subClass: `${s} ⊑ ${o}`,
579
- partOf: `${s} partOf ${o}`,
580
- about: `${s} about ${o}`,
581
- aboutPatient: `${s} aboutPatient ${o}`,
582
- requiresTask: `${s} requires ${o}`,
583
- priority: `${s} priority ${o}`,
584
- };
585
- return tri[p] || `${s} ${p} ${o}`;
586
- }
587
-
588
- function formatFacts(facts) {
589
- const groups = {};
590
- for (const f of facts) {
591
- (groups[f.pred] ||= []).push(f);
592
- }
593
- const order = ['isA', 'subClass', 'partOf', 'about', 'aboutPatient', 'requiresTask', 'priority'];
594
- const lines = [];
595
- for (const pred of order) {
596
- if (!groups[pred]) continue;
597
- const sorted = groups[pred].slice().sort((a, b) => (a.s + a.o).localeCompare(b.s + b.o));
598
- for (const f of sorted) lines.push(prettyFact(f));
599
- }
600
- for (const pred of Object.keys(groups)) {
601
- if (order.includes(pred)) continue;
602
- const sorted = groups[pred].slice().sort((a, b) => (a.s + a.o).localeCompare(b.s + b.o));
603
- for (const f of sorted) lines.push(prettyFact(f));
604
- }
605
- return lines;
606
- }
607
-
608
- // ---- Checks
609
- function runChecks(facts, checksSpec) {
610
- const factSet = new Set(facts.map(key));
611
- const out = [];
612
- for (let i = 0; i < checksSpec.length; i++) {
613
- const chk = checksSpec[i];
614
- const k = key(chk.pattern);
615
- const passed = factSet.has(k);
616
- out.push({ i: i + 1, name: chk.name, passed });
617
- }
618
- return out;
619
- }
620
-
621
- function renderChecks(results) {
622
- if (!results.length) return '(no checks)';
623
- const lines = [];
624
- for (const r of results) {
625
- lines.push(`${r.passed ? '✅' : '❌'} ${String(r.i).padStart(2, ' ')} — ${r.name}`);
626
- }
627
- const passCt = results.filter((r) => r.passed).length;
628
- lines.push(`\nSummary: ${passCt}/${results.length} PASS`);
629
- return lines.join('\n');
630
- }
631
-
632
- // ---- Care Plan Summary (uses strongest priority per patient)
633
- function summarizeCare(facts) {
634
- const tasksByP = new Map();
635
- for (const f of facts) {
636
- if (f.pred === 'requiresTask') {
637
- if (!tasksByP.has(f.s)) tasksByP.set(f.s, new Set());
638
- tasksByP.get(f.s).add(f.o);
639
- }
640
- }
641
- const best = bestPriorities(facts);
642
- const patients = new Set([...tasksByP.keys(), ...best.keys()]);
643
- if (!patients.size) return '(no patients with derived care tasks)';
644
- const lines = [];
645
- for (const p of [...patients].sort()) {
646
- const pr = best.get(p) || 'Routine';
647
- const tasks = [...(tasksByP.get(p) || [])].sort().join(', ');
648
- lines.push(`${p}: priority ${pr}${tasks ? ' — tasks: ' + tasks : ''}`);
649
- }
650
- return lines.join('\n');
651
- }
652
-
653
- // ---- Orchestration
654
- function parseJSON(text, label) {
655
- try {
656
- return JSON.parse(text);
657
- } catch (e) {
658
- throw new Error(`${label} JSON error: ${e.message}`);
659
- }
660
- }
661
-
662
- function toPolicies(spec) {
663
- return spec.map((r) => ({
664
- id: r.id || '(unnamed)',
665
- if: r.if || [],
666
- then: r.then || [],
667
- explain: r.explain || '',
668
- }));
669
- }
670
-
671
- function buildDataObj(spec) {
672
- return spec;
673
- }
674
-
675
- async function runARC() {
676
- els.status.textContent = 'Parsing JSON…';
677
- els.answer.textContent = els.reason.textContent = els.checks.textContent = 'computing…';
678
- els.summary.textContent = '(run to populate)';
679
- els.diag.textContent = '';
680
- try {
681
- const dataSpec = parseJSON(els.dataTA.value, 'Data');
682
- const polSpec = parseJSON(els.policyTA.value, 'Policies');
683
- const checksSpec = parseJSON(els.checksTA.value, 'Checks');
684
- const data = buildDataObj(dataSpec);
685
- const policies = toPolicies(polSpec);
686
-
687
- els.status.textContent = 'Reasoning…';
688
- const { facts, derived, answerText, reasonText } = derive(data, policies);
689
-
690
- els.answer.textContent = answerText || '(no new derivations)';
691
- els.reason.textContent = reasonText || '(no explanations available)';
692
-
693
- els.status.textContent = 'Running checks…';
694
- const checkResults = runChecks(facts, checksSpec);
695
- els.checks.textContent = renderChecks(checkResults);
696
-
697
- // Summary (strongest priority)
698
- els.summary.textContent = summarizeCare(facts);
699
-
700
- els.status.textContent = 'Done.';
701
- } catch (e) {
702
- console.error(e);
703
- els.status.textContent = 'Error';
704
- els.answer.textContent = '(failed)';
705
- els.reason.textContent = '(failed)';
706
- els.checks.textContent = '(failed)';
707
- els.summary.textContent = '(failed)';
708
- els.diag.textContent = e.message; // see parse error here if any
709
- }
710
- autoResize(els.dataTA);
711
- autoResize(els.policyTA);
712
- autoResize(els.checksTA);
713
- }
714
-
715
- function showReasonOnly() {
716
- runARC().then(() => {
717
- window.scrollTo({ top: $('reason').getBoundingClientRect().top + window.scrollY - 12, behavior: 'smooth' });
718
- });
719
- }
720
-
721
- els.runBtn.addEventListener('click', runARC);
722
- els.reasonBtn.addEventListener('click', showReasonOnly);
723
- window.addEventListener('DOMContentLoaded', runARC);
724
- </script>
725
- </body>
726
- </html>