joycraft 1.1.1 → 1.1.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.
Files changed (29) hide show
  1. package/README.md +57 -16
  2. package/dist/cli.js +50 -9
  3. package/dist/cli.js.map +1 -1
  4. package/dist/joycraft-release.json +1 -1
  5. package/package.json +3 -3
  6. package/payload/.agents/skills/joycraft-cleanup/SKILL.md +81 -34
  7. package/payload/.agents/skills/joycraft-context/SKILL.md +30 -4
  8. package/payload/.agents/skills/joycraft-entry/SKILL.md +19 -8
  9. package/payload/.agents/skills/joycraft-session-end/SKILL.md +8 -3
  10. package/payload/.joycraft/assets/artifacts/kit.css +8 -0
  11. package/payload/.joycraft/assets/artifacts/kit.js +163 -21
  12. package/payload/.joycraft/assets/artifacts/transports.js +14 -3
  13. package/payload/.joycraft/references/artifacts.md +21 -2
  14. package/payload/.joycraft/references/cleanup.md +109 -3
  15. package/payload/.joycraft/references/context.md +64 -2
  16. package/payload/.joycraft/references/doc-cleanup-LICENSE.md +23 -0
  17. package/payload/.joycraft/references/knowledge.md +58 -0
  18. package/payload/.joycraft/references/setup.md +128 -138
  19. package/payload/.joycraft/references/update.md +5 -3
  20. package/payload/.joycraft/runtime/artifacts/decisions.mjs +16 -5
  21. package/payload/.joycraft/runtime/artifacts/server.mjs +14 -1
  22. package/payload/.joycraft/runtime/cleanup.mjs +95 -8
  23. package/payload/.joycraft/runtime/config.mjs +5 -3
  24. package/payload/.joycraft/runtime/review-tools.mjs +55 -8
  25. package/payload/.joycraft/runtime/update-check.mjs +38 -8
  26. package/payload/.joycraft/runtime/wiring.mjs +156 -0
  27. package/payload/.joycraft/templates/joycraft.yaml +2 -0
  28. package/payload/.joycraft/templates/project-context.md +6 -1
  29. package/payload/PIN +25 -22
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "releaseVersion": "1.1.1",
3
+ "releaseVersion": "1.1.2",
4
4
  "manifestSchemas": [
5
5
  1
6
6
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "joycraft",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "Install and update Joycraft, a skill bundle and runtime for agent-led software work, in any project",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,8 +13,8 @@
13
13
  "payload"
14
14
  ],
15
15
  "joycraft": {
16
- "release": "1.1.1",
17
- "summary": "Fixes from the 1.0.1 and 1.1 re-reviews: cleanup reads code fences correctly, trace reads folders like tests/[slug], prune skips the tree it runs from, and stale locks are taken over safely.",
16
+ "release": "1.1.2",
17
+ "summary": "After install, your agent builds Joycraft's context map with you and keeps it current; init, update and doctor report an unwired project; cleanup follows doc-cleanup; the update prompt lists every release since yours.",
18
18
  "autoSafeEligible": false
19
19
  },
20
20
  "scripts": {
@@ -1,41 +1,88 @@
1
1
  ---
2
2
  name: joycraft-cleanup
3
- description: Find stale or unreachable project knowledge (finished features left in the working folder, context pages that link to working material, broken or orphaned pages, pages whose code changed, leftover worktrees) and fix what the user approves.
3
+ description: Audit project docs and the AGENTS.md context map for rot (stale claims, finished plans and logs, contradictions, dead paths, drifted authorities, unreachable pages), check each claim against the code, propose trimming an AGENTS.md that is too long, and change only what the user approves. Runs at every session end (scoped to what the session touched) and after a feature is archived (whole project); also use for "clean up the docs", "audit the docs", "what in our docs is stale", "AGENTS.md is too long", or when cleanup.mjs reports findings.
4
4
  compatibility: Requires Node.js 22+ and the installed .joycraft runtime. Git improves the code-drift and worktree checks.
5
5
  ---
6
6
 
7
7
  # Joycraft Cleanup
8
8
 
9
- Use when the user asks to clean up docs, remove stale material or check that
10
- project knowledge is current, and at session end when `status.mjs` or the
11
- archive step leaves loose ends. It keeps the context home trustworthy; it does
12
- not change product decisions.
13
-
14
- Run the report from the project root:
15
-
16
- ```sh
17
- node .joycraft/runtime/cleanup.mjs
18
- ```
19
-
20
- Exit 0 means no findings; exit 2 means findings. The script reads
21
- `joycraft.yaml` for `paths` and the `cleanup.impact` map (code globs → context
22
- pages) and never edits a file. Read `.joycraft/references/cleanup.md` for each
23
- check and its usual fix.
24
-
25
- Then, for each finding:
26
-
27
- 1. Read the files it names before proposing anything. For `impact-drift`,
28
- read the listed commits' changes and the page; the page may still be true.
29
- 2. Propose one concrete fix per finding: the exact link, page, section or
30
- command. Group findings by fix, not by check.
31
- 3. Show the proposals to the user as a rendered page (the decision artifact for
32
- choices, or an HTML page), never only as Markdown in chat. Ask once.
33
- 4. Apply only what the user approves. Move durable facts into the context home
34
- before an archive. Archive only through the session-end archive path. Remove
35
- an unknown worktree only after checking it for unmerged work and with the
36
- user's approval.
37
- 5. Run the report again and give the remaining findings with their reasons.
38
-
39
- Never delete a context page to clear a finding; merge or redirect it. Do not
40
- invent facts to refresh a stale page: when the code does not settle it, record
41
- the question in the owning brief.
9
+ Keep project docs true and the context map lean. Treat every doc claim as a
10
+ hypothesis and the repository as the evidence. The homes the map points to must
11
+ state the current truth; see [knowledge guidance](../../../.joycraft/references/knowledge.md)
12
+ for that rule. This method is adapted from doc-cleanup by aka-luan
13
+ ([MIT](../../../.joycraft/references/doc-cleanup-LICENSE.md)), brought in by David Moshal.
14
+
15
+ Work in two passes: diagnose and report without editing, then execute only what
16
+ the user approves. Approval to edit is not approval to commit. Read
17
+ [cleanup reference](../../../.joycraft/references/cleanup.md) for the doc roles,
18
+ the checks, the AGENTS.md trim and the execution playbook.
19
+
20
+ When setup calls this skill, run steps 1–2 only and hand the findings back to
21
+ setup: no report page and no stop. Setup asks about them in its interview and
22
+ shows the agreed fixes on its one diff page.
23
+
24
+ When session end calls this skill, the scope is AGENTS.md, CLAUDE.md, the docs the
25
+ session changed and the context pages they link (the whole project after an
26
+ archive). Run steps 1–3, but the report goes on the session-end page instead of a
27
+ page of its own; run step 4 only for the fixes the user approves there.
28
+
29
+ ## 1. Inventory
30
+
31
+ List every in-scope Markdown file (skip generated, dependency, VCS, installed
32
+ skill and runtime files, and paths the user excludes) with its line count and
33
+ [role](../../../.joycraft/references/cleanup.md#doc-roles): entry, required,
34
+ reference or historical. Follow every reading pointer in the entry docs and mark it
35
+ resolved, dead or external. Rot costs more the more often a file is read. In a
36
+ large repo, do the entry docs and their pointers first, then area by area, and say
37
+ what you have not read.
38
+
39
+ ## 2. Diagnose without editing
40
+
41
+ Run `node .joycraft/runtime/cleanup.mjs` first: exit 2 means findings, and each
42
+ is evidence to confirm, not a verdict. Then read each doc for the six rot
43
+ patterns: completed-work logs, executed plans, internal contradictions, stale
44
+ claims, dead paths, and authority drift. Check every suspected hit against the
45
+ repository (file lookup, search, config, tests, Git history) and record its
46
+ location, the claim, the evidence, your confidence and the smallest disposition:
47
+ keep, correct, condense, move, archive or banner. Code proves what is
48
+ implemented, not what was intended; when a doc may define the contract, report
49
+ the mismatch as unresolved authority drift.
50
+
51
+ Mark the load-bearing content that must survive: hard rules, active decisions,
52
+ recurring traps, do-not-do lines and domain vocabulary.
53
+
54
+ An entry file loads every session, so it holds the project's identity, its rules
55
+ and the context map. When it carries file tables, folder trees, workflow or
56
+ command sections, code or data-flow walkthroughs, or gotcha lists, propose moving
57
+ each into a linked context page with a map row that says when to read it. Never
58
+ propose moving, rewording or reformatting rules: ALWAYS / ASK FIRST / NEVER lists
59
+ and any other must or never section stay exactly as they are. A gotcha that is a
60
+ rule ("Never reference absolute paths") is a rule: it stays.
61
+
62
+ ## 3. Report and stop
63
+
64
+ Order findings by reading frequency × how badly they would mislead. For each,
65
+ give the claim, the evidence, the consequence and the proposed change. Then give
66
+ a per-file plan, list unresolved decisions separately, and name the load-bearing
67
+ content that will remain. Show it as a rendered page (the decision artifact for
68
+ choices, otherwise an HTML page), not only as Markdown in chat.
69
+
70
+ Stop for approval. Until the user approves, change no file in the project: no
71
+ edits, no new pages, no "safe" fixes.
72
+
73
+ ## 4. Execute the approved plan
74
+
75
+ Apply only approved changes, re-checking each fact against the code just before
76
+ writing it, with the playbook in the cleanup reference. Never delete a context
77
+ page to clear a finding; merge or redirect it. When the code does not settle a
78
+ fact, record the question in the owning brief rather than inventing an answer.
79
+ Remove an unknown worktree only after checking it for unmerged work.
80
+
81
+ ## 5. Verify and hand off
82
+
83
+ Run `cleanup.mjs` again. Check that every link in touched files resolves, that
84
+ archives match their sources, that the load-bearing content survives (rules
85
+ byte-identical), that only approved Markdown changed, and that no new
86
+ contradiction appeared. Report the changed files, archive mappings, remaining
87
+ findings with reasons and unresolved decisions. Offer a docs-only commit with a
88
+ specific message; commit only when the user says yes.
@@ -1,14 +1,17 @@
1
1
  ---
2
2
  name: joycraft-context
3
- description: Find and rank relevant project decisions, references and implementation files when a request needs context beyond the current files.
4
- compatibility: Requires Node.js 22+ and the installed .joycraft runtime for retrieval. Git improves tracked-file discovery, with local search fallback.
3
+ description: Find, add, change or remove project context. Use when a request needs decisions, references or files beyond the current ones ("what does the map say about billing?"), when the user says "add this to the project context", "remember that ...", "that's no longer true", "forget/remove that rule", or hands over meeting notes, a screenshot or pasted text whose facts the project should keep.
4
+ compatibility: Requires Node.js 22+ and the installed .joycraft runtime for retrieval and the map check. Git improves tracked-file discovery, with local search fallback.
5
5
  ---
6
6
 
7
7
  Read the project's boundaries and context map first. If these are missing during
8
8
  authorized setup or implementation, use the first-use procedure in
9
9
  [first-use setup](../../../.joycraft/references/setup.md); retrieval alone does not create project
10
- knowledge. Keep read-only research read-only. Use a concrete request to
11
- find local candidates and their bounded snippets:
10
+ knowledge. Keep read-only research read-only.
11
+
12
+ ## Find context
13
+
14
+ Use a concrete request to find local candidates and their bounded snippets:
12
15
 
13
16
  ```sh
14
17
  node .joycraft/runtime/context/cli.mjs --query "<current request>"
@@ -34,3 +37,26 @@ conditional discovery; it is navigation, not a decision authority or constraint.
34
37
  Do not dump entire files, secrets or transcripts into a scoring request. Reuse
35
38
  settled decisions, and surface contradictions affecting scope or consequential
36
39
  choices while continuing understood authorized work.
40
+
41
+ ## Add, change or remove context
42
+
43
+ When the user asks to record, correct or drop project knowledge, or gives you
44
+ notes, a screenshot or pasted text to capture, follow
45
+ [knowledge guidance](../../../.joycraft/references/knowledge.md) and the
46
+ "Changing context" steps in `.joycraft/references/context.md`. In short:
47
+
48
+ 1. Split the input into separate facts. From notes keep only what was settled or
49
+ observed; list action items, open questions and ideas as left out.
50
+ 2. Search the live homes for each subject first. A fact already stated is
51
+ rewritten in place, never stated twice.
52
+ 3. Add: write the fact in its one home. A kind of fact the map has no home for
53
+ gets a new page and a map row with a real "read when".
54
+ 4. Change: rewrite the statement in place; the reason and the replaced choice go
55
+ in a new decision-log entry.
56
+ 5. Remove: delete the live statement wherever it appears and add a decision-log
57
+ entry that names what was removed and why. A page left with no facts is
58
+ deleted together with its map row and any links to it.
59
+ 6. Show the proposed changes as a diff and write only on the user's yes. A
60
+ request that already says to apply the change counts as the yes.
61
+ 7. Run `node .joycraft/runtime/cleanup.mjs` and fix any `missing-path`,
62
+ `unmapped`, `orphan` or `broken-link` finding the change caused.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: joycraft-entry
3
- description: Set up missing project guidance on first use, then turn a repair, feature, or mixed request into a context-backed brief and the next useful action.
3
+ description: Start any Joycraft work. After Joycraft is installed, or when asked to "set up Joycraft" or "check the context map", read the project, interview the user and build the context map in AGENTS.md; then turn a repair, feature, or mixed request into a context-backed brief and the next useful action.
4
4
  compatibility: Setup and routing helpers require Node.js 22+ and the installed .joycraft runtime only when used; ordinary brief and context navigation has no project-stack prerequisite.
5
5
  ---
6
6
 
@@ -8,12 +8,23 @@ Run `node .joycraft/runtime/update-check.mjs check` first, once per session. If
8
8
  prints nothing, say nothing. If it prints JSON, follow
9
9
  [updates](../../../.joycraft/references/update.md).
10
10
 
11
+ Then run `node .joycraft/runtime/wiring.mjs --root .`. The CLI cannot write
12
+ the project's context map, because it knows nothing about the project; you
13
+ build it. When the check exits 2, or right after an install, or when the user
14
+ asks to set up Joycraft or check the context map, say in one line that you are
15
+ setting up Joycraft's context map first, follow
16
+ [setup](../../../.joycraft/references/setup.md), then continue the original
17
+ request. A read-only request gets the findings reported, not written.
18
+
19
+ The check's `advice` lists `unmapped-areas`: the areas setup has not read yet,
20
+ kept under `## Not yet mapped` in the project context page. When a request
21
+ touches a listed area, map that area first: read it, propose its map rows and
22
+ homes, write them on the user's yes, and remove the area from the list. Advice
23
+ alone does not start a full setup.
24
+
11
25
  Read existing project instructions first. During an upgrade, inspect the installed
12
26
  manifest’s `legacyConflicts` and reconcile competing old skill discovery before
13
- using routing advice; preserved custom content is not a completed migration. On first use, explicit setup/init, or
14
- when shared guidance or its context pointers are missing, follow
15
- [first-use setup](../../../.joycraft/references/setup.md). Establish the missing knowledge homes
16
- from the current request and repository facts, preserving existing guidance.
27
+ using routing advice; preserved custom content is not a completed migration.
17
28
  On a bare project, offer the
18
29
  [kickoff](../../../.joycraft/references/setup.md#kickoff-for-a-new-project)
19
30
  in one line before any brief or scaffold, and run it when the user asks for it on
@@ -21,8 +32,7 @@ any project. On first entry, setup and upgrade, also run the review-loop plan in
21
32
  [review loop tools](../../../.joycraft/references/setup.md#review-loop-tools);
22
33
  install nothing without the user's yes.
23
34
  Continue the user's work after setup; setup alone does not require a feature
24
- brief, spec queue, app scaffold, or a new interview. A read-only request stays
25
- read-only; report missing setup without writing it.
35
+ brief, spec queue or app scaffold.
26
36
 
27
37
  Before assigning work, read `.joycraft/preferences.json` when it exists. Reuse
28
38
  its explicit model, effort, role, concurrency, and verification choices, then
@@ -74,7 +84,8 @@ says `docs/features`, `docs/archive` or `docs/context`.
74
84
 
75
85
  **Show documents as pages.** A brief, plan, spec set or review that the user must
76
86
  read or approve is also rendered, never left as Markdown in chat: the decision
77
- artifact for a brief, an HTML page for anything else. Open it and say where it is.
87
+ artifact for a brief, an HTML page for anything else. Show it as
88
+ [showing a page](../../../.joycraft/references/artifacts.md#showing-a-page) says and give its path.
78
89
  If the project's `AGENTS.md` lacks this rule or its context-map row for
79
90
  `.joycraft/references/artifacts.md`, add them as `setup.md` describes.
80
91
 
@@ -35,8 +35,6 @@ any feature listed as ready to archive. Then preview
35
35
  `node .joycraft/runtime/worktrees.mjs prune` and apply it with `--apply`: it
36
36
  removes only clean, integrated trees of done specs and keeps failed, blocked or
37
37
  unknown trees with their reason. Report kept trees and their size from `list`.
38
- Then run `node .joycraft/runtime/cleanup.mjs` and report its findings; offer
39
- `joycraft-cleanup` when any remain.
40
38
  When this session coordinated a queue and no work on it remains, release the
41
39
  lease with `node .joycraft/runtime/coordinator.mjs release --queue <queue> --session <your-session-id>`. See [worker isolation](../../../.joycraft/references/worktrees.md)
42
40
  when the session used parallel mutable workers.
@@ -46,7 +44,14 @@ that condition and arrange a fresh review after it is corrected. Do not create
46
44
  an unchanged-code fix round. The existing completion process remains the sole
47
45
  owner of acceptance and status changes.
48
46
 
49
- Before archival, update the existing owning context reference and its pointers only when accepted work established reusable project knowledge: record the affected boundary, current coupled sources, observable check, and known limit. Keep accepted observations distinct from proposals, and leave product choices in the brief's decision authority rather than copying them into a competing context record. Do not create a global map or rewrite unrelated context for a local change.
47
+ Before ending, and before any archival, route each reusable fact the session established (a decision with its reason, a trap, a reference, a production fact) to its one home per [knowledge guidance](../../../.joycraft/references/knowledge.md). Rewrite a changed fact in place and put its reason in the decision log; add a context-map row for a new home; keep each touched row's "read when" true. Leave feature intent in the brief. A session with nothing reusable changes no context file.
48
+
49
+ Then audit the docs without being asked: run `joycraft-cleanup` in its
50
+ session-end mode. Its scope is AGENTS.md, CLAUDE.md, every doc this session
51
+ changed and the context pages they link; after a feature is archived, the whole
52
+ project. Put its findings on the session-end page with the rest of the report and
53
+ apply only the fixes the user approves there. With no findings, say so in one
54
+ line.
50
55
 
51
56
  When independent reports suggest a reusable failure lesson, use the compact, conditional process in [recurring failure guidance](../../../.joycraft/references/recurring-failures.md): keep only a source-linked shortlist in active task material, inspect current sources before relying on history, and route any proposed lesson as exact next-worker inputs through the existing dispatch path.
52
57
 
@@ -61,6 +61,14 @@ html[data-jca-theme] body { margin: 0; background: var(--canvas); color: var(--i
61
61
  .jca-message-success { border-color: var(--accent); background: var(--accent-soft); }
62
62
  .jca-message-quiet { color: var(--muted); }
63
63
  .jca-actions { display: flex; flex-wrap: wrap; gap: .55rem; margin: .8rem 0 1rem; }
64
+ .jca-source-notice { margin: 1.2rem 0; padding: .8rem 1rem; border: 1px solid var(--accent); border-left-width: 4px; border-radius: 8px; background: var(--accent-soft); font-size: .92rem; }
65
+ .jca-source-notice h2 { margin: 0 0 .45rem; font-size: 1rem; }
66
+ .jca-source-notice p, .jca-source-notice ul { margin: .4rem 0; }
67
+ .jca-source-notice a { color: var(--accent); }
68
+ .jca-source-notice-error { border-color: var(--error); background: var(--error-bg); }
69
+ .jca-source-notice-error h2, .jca-source-notice-error > p:first-of-type { color: var(--error); }
70
+ .jca-changed { margin: 0 0 1rem; color: var(--error); font-size: .9rem; font-weight: 650; }
71
+ .jca-visually-hidden { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
64
72
  .joycraft-artifact button { appearance: none; border: 1px solid var(--control-line); border-radius: 8px; padding: .56rem .82rem; color: var(--accent); background: var(--paper); font: inherit; font-size: .88rem; font-weight: 600; cursor: pointer; }
65
73
  .joycraft-artifact button:hover { border-color: var(--accent); background: var(--accent-soft); }
66
74
  .joycraft-artifact .jca-save-one, .joycraft-artifact [data-jca-save-all] { color: var(--accent-text); background: var(--accent); border-color: var(--accent); }
@@ -41,6 +41,39 @@
41
41
  });
42
42
  }
43
43
 
44
+ // What a person decides from: the question, its options, and its recorded state.
45
+ function questionSignature(question) {
46
+ return JSON.stringify({
47
+ question: question.question || '',
48
+ options: (question.options || []).map(function (option) {
49
+ return { value: option.value, label: option.label || '', description: option.description || '', requiresNote: Boolean(option.requiresNote) };
50
+ }),
51
+ status: question.status || '',
52
+ answer: question.answer == null ? null : question.answer,
53
+ note: question.note == null ? '' : question.note
54
+ });
55
+ }
56
+
57
+ // Questions that differ between two models: changed, added or removed, in display order.
58
+ function changedQuestions(before, after) {
59
+ var oldQuestions = (before && before.questions) || [];
60
+ var newQuestions = (after && after.questions) || [];
61
+ var oldById = Object.create(null);
62
+ oldQuestions.forEach(function (question) { oldById[question.id] = question; });
63
+ var newIds = Object.create(null);
64
+ var changes = [];
65
+ newQuestions.forEach(function (question) {
66
+ newIds[question.id] = true;
67
+ var previous = oldById[question.id];
68
+ if (!previous) changes.push({ id: question.id, question: question.question || question.id, change: 'added' });
69
+ else if (questionSignature(previous) !== questionSignature(question)) changes.push({ id: question.id, question: question.question || question.id, change: 'changed' });
70
+ });
71
+ oldQuestions.forEach(function (question) {
72
+ if (!newIds[question.id]) changes.push({ id: question.id, question: question.question || question.id, change: 'removed' });
73
+ });
74
+ return changes;
75
+ }
76
+
44
77
  function mount(config) {
45
78
  if (!config || !config.element) throw new Error('JoycraftArtifacts.mount requires an element.');
46
79
  var root = config.element;
@@ -56,13 +89,21 @@
56
89
  var saving = false;
57
90
  var destroyed = false;
58
91
  var copyFallback = '';
59
- var sourceChanged = false;
92
+ // Persistent notice after the brief changed under this page. It stays until dismissed,
93
+ // so selecting options (which updates the status line) never hides it.
94
+ var sourceNotice = null;
95
+ // The notice element is created once and reused, so a re-render does not re-announce it.
96
+ var noticeElement = null, noticeKey = '';
60
97
  var message = transport ? 'Loading saved responses…' : 'Read-only preview. A response transport is not available.';
61
98
  var messageKind = transport ? 'quiet' : 'notice';
62
99
 
63
100
  function isReadOnly(question) {
64
101
  return !writable || ['clarified', 'settled', 'backlogged', 'discarded'].indexOf(question.status) !== -1;
65
102
  }
103
+ // A saved answer keeps its note open: the note can be added or changed and saved again.
104
+ function canEditNote(question) {
105
+ return writable && (!isReadOnly(question) || question.status === 'clarified');
106
+ }
66
107
  function dirty() { return !sameResponses(draft, saved); }
67
108
  function setMessage(kind, value) { messageKind = kind; message = value; }
68
109
  function statusLabel(status) {
@@ -87,11 +128,11 @@
87
128
 
88
129
  function unsavedAnswers() { return copiedResponses(draft).filter(function (item) {
89
130
  var q = model.questions.find(function (candidate) { return candidate.id === item.id; });
90
- return q && !isReadOnly(q) && !sameResponses({ value: item }, { value: saved[item.id] || {} });
131
+ return q && canEditNote(q) && !sameResponses({ value: item }, { value: saved[item.id] || {} });
91
132
  }); }
92
133
 
93
134
  async function save(question) {
94
- if (!transport || !writable || saving || loading || sourceChanged) return;
135
+ if (!transport || !writable || saving || loading) return;
95
136
  var pendingAnswers = unsavedAnswers();
96
137
  var problem = question ? validation(question) : pendingAnswers.map(function (item) {
97
138
  var q = (model.questions || []).filter(function (candidate) { return candidate.id === item.id; })[0];
@@ -105,15 +146,46 @@
105
146
  var result = await transport.save({ revision: revision, answers: answers });
106
147
  if (destroyed) return;
107
148
  applyLoaded(result, Boolean(question), answers.map(function (answer) { return answer.id; }));
149
+ if (sourceNotice && sourceNotice.conflict) sourceNotice.saved = true;
108
150
  setMessage('success', (result && result.message) || 'Saved in artifact — awaiting brief sync.');
109
151
  } catch (error) {
110
- setMessage('error', 'Could not save. Your edits are still here. ' + (error && error.message ? error.message : 'Try refreshing before saving again.'));
152
+ if (error && error.conflict) await reloadAfterConflict(error);
153
+ else setMessage('error', 'Could not save. Your edits are still here. ' + (error && error.message ? error.message : 'Try refreshing before saving again.'));
111
154
  } finally { saving = false; render(); }
112
155
  }
156
+ // The source changed after this page loaded: reload it, keep drafts for unchanged
157
+ // questions, and name the questions that changed in the persistent notice.
158
+ async function reloadAfterConflict(error) {
159
+ var reason = error && error.message ? error.message : 'The source changed after this page loaded.';
160
+ if (typeof transport.load !== 'function') { setMessage('error', 'Not saved. ' + reason + ' Reload the page to continue.'); return; }
161
+ try {
162
+ var latest = await transport.load();
163
+ if (destroyed) return;
164
+ applyLoaded(latest, true);
165
+ } catch (loadError) {
166
+ setMessage('error', 'Not saved. ' + reason + ' Reloading the source also failed: ' + (loadError && loadError.message ? loadError.message : 'unknown error') + '. Your edits are still here.');
167
+ return;
168
+ }
169
+ sourceNotice = sourceNotice || { changes: [], viewChanged: false };
170
+ sourceNotice.conflict = reason;
171
+ sourceNotice.saved = false;
172
+ setMessage('error', 'Not saved: ' + reason + ' The page now shows the current source. Your other answers are kept; save again.');
173
+ }
174
+ function mergeNotice(changes, viewChanged) {
175
+ var current = sourceNotice || { changes: [], viewChanged: false, conflict: '' };
176
+ changes.forEach(function (change) {
177
+ var existing = current.changes.filter(function (item) { return item.id === change.id; })[0];
178
+ if (existing) { existing.question = change.question; if (change.change === 'removed' || existing.change !== 'added') existing.change = change.change; }
179
+ else current.changes.push(change);
180
+ });
181
+ current.viewChanged = current.viewChanged || viewChanged;
182
+ sourceNotice = current;
183
+ }
184
+ function changedIds() { return sourceNotice ? sourceNotice.changes.map(function (change) { return change.id; }) : []; }
113
185
  function applyLoaded(result, preserveDraft, confirmedIds) {
114
186
  confirmedIds = confirmedIds || [];
115
187
  if (!result) throw new Error('The response transport returned no state.');
116
- var oldRevision = revision;
188
+ var oldModel = model;
117
189
  var oldViewRevision = viewRevision;
118
190
  var pending = Object.assign(Object.create(null), draft);
119
191
  var previouslySaved = Object.assign(Object.create(null), saved);
@@ -123,24 +195,31 @@
123
195
  writable = Boolean(result.writable);
124
196
  storage = result.storage || storage;
125
197
  saved = responseMap(result.responses);
198
+ // Portable pages store only their own answers; start a recorded answer from the brief so its note can change.
199
+ (model.questions || []).forEach(function (q) {
200
+ if (q.status === 'clarified' && q.answer && !saved[q.id]) saved[q.id] = { answer: q.answer, note: q.note || '' };
201
+ });
126
202
  draft = Object.assign(Object.create(null), saved);
127
- var changedSource = oldViewRevision !== viewRevision || (!confirmedIds.length && oldRevision && revision && oldRevision !== revision);
203
+ // Our own save changes the saved questions; any other difference came from elsewhere.
204
+ var changes = changedQuestions(oldModel, model).filter(function (change) { return confirmedIds.indexOf(change.id) === -1; });
205
+ var viewChanged = Boolean(oldViewRevision && viewRevision && oldViewRevision !== viewRevision);
206
+ if (changes.length || viewChanged) mergeNotice(changes, viewChanged);
207
+ // Only questions that changed in this load lose a pending choice; earlier ones were already re-chosen.
208
+ var changed = changes.map(function (change) { return change.id; });
128
209
  if (preserveDraft && !sameResponses(pending, previouslySaved)) {
129
210
  Object.keys(pending).forEach(function (id) {
130
- if (confirmedIds.indexOf(id) !== -1 || !model.questions.some(function (q) { return q.id === id && !isReadOnly(q); })) return;
211
+ if (confirmedIds.indexOf(id) !== -1) return;
212
+ var question = (model.questions || []).filter(function (q) { return q.id === id; })[0];
213
+ if (!question || !canEditNote(question)) return;
131
214
  var before = previouslySaved[id] || { answer: '', note: '' };
132
215
  var after = pending[id] || { answer: '', note: '' };
133
- if (before.answer !== after.answer || (before.note || '') !== (after.note || '')) {
134
- if (changedSource) draft[id] = { answer: '', note: after.note || '' };
135
- else draft[id] = after;
136
- }
216
+ if (before.answer === after.answer && (before.note || '') === (after.note || '')) return;
217
+ // A changed question needs a fresh choice; its note text is kept. Unchanged questions keep the draft.
218
+ if (changed.indexOf(id) !== -1) draft[id] = { answer: isReadOnly(question) ? ((saved[id] || {}).answer || '') : '', note: after.note || '' };
219
+ else draft[id] = after;
137
220
  });
138
- if (changedSource) {
139
- sourceChanged = true;
140
- setMessage('notice', 'The source changed. Your unsaved note text remains, but choose responses again before saving.');
141
- }
142
221
  }
143
- if (result.message && !sourceChanged) setMessage('notice', result.message);
222
+ if (result.message) setMessage('notice', result.message);
144
223
  }
145
224
  async function refresh() {
146
225
  if (!transport || typeof transport.load !== 'function' || loading) return;
@@ -186,13 +265,74 @@
186
265
  if (messageNode) { messageNode.className = 'jca-message jca-message-' + messageKind; messageNode.textContent = message; }
187
266
  var footer = root.querySelector('.jca-footer');
188
267
  if (footer) footer.textContent = writable ? (dirty() ? 'Unsaved response edits are on this page.' : countText() + '.') : 'Responses are read-only in this artifact.';
189
- root.querySelectorAll('[data-jca-save-all]').forEach(function (button) { button.disabled = !writable || saving || sourceChanged || !unsavedAnswers().length; });
268
+ root.querySelectorAll('[data-jca-save-all]').forEach(function (button) { describeDisabled(button, saveAllBlocked()); });
269
+ }
270
+ function saveAllBlocked() {
271
+ if (!writable) return 'Responses are read-only in this artifact.';
272
+ if (saving) return 'A save is in progress.';
273
+ if (loading) return 'Saved responses are still loading.';
274
+ if (!unsavedAnswers().length) return 'Nothing to save: choose a response first.';
275
+ return '';
276
+ }
277
+ function saveOneBlocked() {
278
+ if (saving) return 'A save is in progress.';
279
+ if (loading) return 'Saved responses are still loading.';
280
+ return '';
281
+ }
282
+ // A disabled button says why: as its tooltip and as its accessible description.
283
+ function describeDisabled(button, reason) {
284
+ button.disabled = Boolean(reason);
285
+ var reasonNode = button.jcaReason;
286
+ if (reasonNode) reasonNode.textContent = reason || '';
287
+ if (reason) {
288
+ button.setAttribute('title', reason);
289
+ if (reasonNode) button.setAttribute('aria-describedby', reasonNode.id);
290
+ } else {
291
+ button.removeAttribute('title');
292
+ button.removeAttribute('aria-describedby');
293
+ }
294
+ }
295
+ // Returns [button, hidden reason element]; both go into the page.
296
+ function saveButton(attributes, reason, reasonId) {
297
+ var button = node('button', Object.assign({ type: 'button' }, attributes));
298
+ button.jcaReason = node('span', { id: reasonId, class: 'jca-visually-hidden' });
299
+ describeDisabled(button, reason);
300
+ return [button, button.jcaReason];
301
+ }
302
+ function renderSourceNotice() {
303
+ if (!sourceNotice) { noticeElement = null; noticeKey = ''; return null; }
304
+ var key = JSON.stringify(sourceNotice);
305
+ if (noticeElement && key === noticeKey) return noticeElement;
306
+ var blocked = sourceNotice.conflict && !sourceNotice.saved;
307
+ if (!noticeElement) noticeElement = node('section', { role: 'alert', 'aria-labelledby': 'jca-source-notice-title' });
308
+ noticeElement.className = 'jca-source-notice' + (blocked ? ' jca-source-notice-error' : '');
309
+ noticeElement.replaceChildren();
310
+ noticeKey = key;
311
+ var banner = noticeElement;
312
+ banner.append(node('h2', { id: 'jca-source-notice-title', text: blocked ? 'Not saved: the source changed after this page loaded'
313
+ : sourceNotice.conflict ? 'The source changed after this page loaded; your later save went through' : 'The source changed after this page loaded' }));
314
+ if (blocked) banner.append(node('p', { text: sourceNotice.conflict }));
315
+ if (sourceNotice.changes.length) {
316
+ banner.append(node('p', { text: sourceNotice.changes.length === 1 ? 'This question changed:' : 'These questions changed:' }));
317
+ var list = node('ul');
318
+ sourceNotice.changes.forEach(function (change) {
319
+ var label = change.change === 'removed' ? ' (removed)' : change.change === 'added' ? ' (new)' : '';
320
+ list.append(node('li', {}, [change.change === 'removed' ? text(change.question + label) : node('a', { href: '#jca-question-' + change.id, text: change.question + label })]));
321
+ });
322
+ banner.append(list);
323
+ banner.append(node('p', { text: 'Choose again where a changed question needs it. Answers to other questions are kept and can be saved now.' }));
324
+ } else {
325
+ banner.append(node('p', { text: sourceNotice.viewChanged ? 'The screenshots or review on this page changed. No question changed; your answers are kept and can be saved now.' : 'No question on this page changed. Your answers are kept and can be saved now.' }));
326
+ }
327
+ banner.append(node('button', { type: 'button', text: 'Dismiss', onclick: function () { sourceNotice = null; setMessage('quiet', dirty() ? 'Unsaved changes.' : 'Source changes reviewed.'); render(); } }));
328
+ return banner;
190
329
  }
191
330
  function renderQuestion(question, index) {
192
331
  var current = draft[question.id] || { answer: '', note: '' };
193
332
  var readOnly = isReadOnly(question);
194
333
  var body = node('section', { class: 'jca-question', id: 'jca-question-' + question.id });
195
334
  body.append(node('div', { class: 'jca-question-kicker', text: 'Decision ' + (index + 1) }), node('h2', { text: question.question }));
335
+ if (changedIds().indexOf(question.id) !== -1) body.append(node('p', { class: 'jca-changed', text: 'Changed in the source since this page loaded. Check it and choose again if needed.' }));
196
336
  body.append(node('p', { class: 'jca-status jca-status-' + (question.status || 'open'), text: statusLabel(question.status) }));
197
337
  if (question.answer) body.append(node('p', { class: 'jca-recorded', text: 'Brief record: ' + question.answer }));
198
338
  (model.comparisons || []).filter(function (comparison) { return comparison.decisionId === question.id; }).forEach(function (comparison) { body.append(renderComparison(comparison)); });
@@ -213,7 +353,7 @@
213
353
  fieldset.append(label);
214
354
  });
215
355
  body.append(fieldset);
216
- var note = node('textarea', { class: 'jca-note', id: 'jca-note-' + question.id, rows: 3, disabled: readOnly, placeholder: 'Optional note' });
356
+ var note = node('textarea', { class: 'jca-note', id: 'jca-note-' + question.id, rows: 3, disabled: !canEditNote(question), placeholder: 'Optional note' });
217
357
  note.value = current.note || '';
218
358
  function syncNoteRequirement() {
219
359
  var selected = (question.options || []).find(function (option) { return option.value === (draft[question.id] || {}).answer; });
@@ -227,7 +367,7 @@
227
367
  note.addEventListener('input', function () { draft[question.id] = { answer: (draft[question.id] || {}).answer || '', note: note.value }; setMessage('quiet', 'Unsaved changes.'); syncLiveUi(); });
228
368
  body.append(noteLabel, note);
229
369
  if (question.answer && question.note) body.append(node('p', { class: 'jca-recorded', text: 'Brief note: ' + question.note }));
230
- if (!readOnly) body.append(node('button', { class: 'jca-save-one', type: 'button', text: 'Save this response', disabled: saving || loading || sourceChanged, onclick: function () { save(question); } }));
370
+ if (canEditNote(question)) body.append.apply(body, saveButton({ class: 'jca-save-one', text: readOnly ? 'Save note' : 'Save this response', onclick: function () { save(question); } }, saveOneBlocked(), 'jca-save-reason-' + question.id));
231
371
  return body;
232
372
  }
233
373
  function renderComparison(comparison) {
@@ -267,11 +407,12 @@
267
407
  header.append(provenance);
268
408
  }
269
409
  page.append(header);
410
+ var notice = renderSourceNotice();
411
+ if (notice) page.append(notice);
270
412
  page.append(node('p', { class: 'jca-message jca-message-' + messageKind, role: messageKind === 'error' ? 'alert' : 'status', text: message }));
271
413
  var actions = node('div', { class: 'jca-actions' });
272
414
  if (transport) actions.append(node('button', { type: 'button', text: loading ? 'Refreshing…' : 'Refresh', disabled: loading || saving, onclick: refresh }));
273
- actions.append(node('button', { type: 'button', 'data-jca-save-all': '', text: 'Save selected answers', disabled: !writable || saving || sourceChanged || !unsavedAnswers().length, onclick: function () { save(); } }));
274
- if (sourceChanged) actions.append(node('button', { type: 'button', text: 'I reviewed the updated source', onclick: function () { sourceChanged = false; setMessage('notice', 'Review acknowledged. Select a response where needed, then save.'); render(); } }));
415
+ actions.append.apply(actions, saveButton({ 'data-jca-save-all': '', text: 'Save selected answers', onclick: function () { save(); } }, saveAllBlocked(), 'jca-save-all-reason'));
275
416
  actions.append(node('button', { type: 'button', text: 'Copy saved', onclick: copySaved }), node('button', { type: 'button', text: 'Download saved', onclick: downloadSaved }));
276
417
  page.append(actions);
277
418
  (model.questions || []).forEach(function (question, index) { page.append(renderQuestion(question, index)); });
@@ -298,4 +439,5 @@
298
439
 
299
440
  global.JoycraftArtifacts = global.JoycraftArtifacts || {};
300
441
  global.JoycraftArtifacts.mount = mount;
442
+ global.JoycraftArtifacts.changedQuestions = changedQuestions;
301
443
  })(window);