project-logbook 0.3.3 → 0.4.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.
Files changed (75) hide show
  1. package/dist/commands/build.js +54 -76
  2. package/dist/commands/init.js +11 -11
  3. package/dist/commands/lint.js +27 -10
  4. package/dist/commands/list.js +18 -18
  5. package/dist/commands/log.js +5 -5
  6. package/dist/commands/new.js +19 -20
  7. package/dist/commands/preview.js +9 -8
  8. package/dist/commands/release.js +6 -6
  9. package/dist/commands/start.js +26 -21
  10. package/dist/commands/status.d.ts +1 -0
  11. package/dist/commands/status.js +138 -0
  12. package/dist/commands/steer.js +9 -9
  13. package/dist/commands/upgrade.js +5 -5
  14. package/dist/index.js +9 -8
  15. package/dist/lib/build-helpers.js +30 -67
  16. package/dist/lib/build-steps.d.ts +20 -0
  17. package/dist/lib/build-steps.js +57 -0
  18. package/dist/lib/config.d.ts +17 -0
  19. package/dist/lib/config.js +27 -3
  20. package/dist/lib/entry-id.d.ts +22 -0
  21. package/dist/lib/entry-id.js +26 -0
  22. package/dist/lib/entry-paths.d.ts +23 -0
  23. package/dist/lib/entry-paths.js +55 -0
  24. package/dist/lib/git-helpers.d.ts +32 -1
  25. package/dist/lib/git-helpers.js +119 -26
  26. package/dist/lib/hast-helpers.d.ts +10 -0
  27. package/dist/lib/hast-helpers.js +22 -0
  28. package/dist/lib/html-attributes.d.ts +17 -0
  29. package/dist/lib/html-attributes.js +17 -0
  30. package/dist/lib/html-escape.d.ts +16 -0
  31. package/dist/lib/html-escape.js +38 -0
  32. package/dist/lib/image-helpers.js +26 -33
  33. package/dist/lib/lint-runner.js +5 -5
  34. package/dist/lib/markdown-processors.d.ts +22 -0
  35. package/dist/lib/markdown-processors.js +68 -0
  36. package/dist/lib/package-version.d.ts +5 -0
  37. package/dist/lib/package-version.js +16 -0
  38. package/dist/lib/rss.d.ts +29 -0
  39. package/dist/lib/rss.js +77 -0
  40. package/dist/lib/styles.js +5 -2
  41. package/dist/lib/template-helpers.d.ts +4 -3
  42. package/dist/lib/template-helpers.js +51 -27
  43. package/dist/lib/template-types.d.ts +2 -2
  44. package/dist/lib/templates.d.ts +12 -3
  45. package/dist/lib/templates.js +59 -52
  46. package/dist/lib/theme.d.ts +37 -0
  47. package/dist/lib/theme.js +50 -0
  48. package/dist/lib/url-helpers.d.ts +13 -0
  49. package/dist/lib/url-helpers.js +27 -0
  50. package/dist/linters/diff-to-narrative.d.ts +6 -0
  51. package/dist/linters/diff-to-narrative.js +114 -0
  52. package/dist/linters/index.js +4 -0
  53. package/dist/linters/technical-log.d.ts +7 -0
  54. package/dist/linters/technical-log.js +72 -0
  55. package/dist/templates/CONTRIBUTING.md +12 -3
  56. package/dist/templates/index.md +10 -6
  57. package/dist/templates/log.md +5 -0
  58. package/dist/templates/logbook-client.js +42 -16
  59. package/dist/templates/steer.txt +21 -5
  60. package/dist/templates/styles.css +121 -0
  61. package/dist/utils/date.d.ts +30 -1
  62. package/dist/utils/date.js +68 -15
  63. package/dist/utils/frontmatter.d.ts +26 -0
  64. package/dist/utils/frontmatter.js +37 -0
  65. package/dist/utils/fs.d.ts +13 -0
  66. package/dist/utils/fs.js +23 -0
  67. package/dist/utils/log-timeline.d.ts +69 -0
  68. package/dist/utils/log-timeline.js +218 -0
  69. package/package.json +4 -2
  70. package/src/templates/CONTRIBUTING.md +12 -3
  71. package/src/templates/index.md +10 -6
  72. package/src/templates/log.md +5 -0
  73. package/src/templates/logbook-client.js +42 -16
  74. package/src/templates/steer.txt +21 -5
  75. package/src/templates/styles.css +121 -0
@@ -1,6 +1,6 @@
1
1
  import fs from 'fs-extra';
2
2
  import { join } from 'node:path';
3
- import chalk from 'chalk';
3
+ import { neutral, warning as warningStyle, successMessage } from '../lib/theme.js';
4
4
  import matter from 'gray-matter';
5
5
  import { getConfig } from '../lib/config.js';
6
6
  import { getActiveEntry } from '../lib/session.js';
@@ -10,7 +10,7 @@ export async function release(options = {}) {
10
10
  const lockfilePath = join(cwd, LOCKFILE_NAME);
11
11
  const active = await getActiveEntry(options, cwd);
12
12
  if (!active) {
13
- console.log(chalk.yellow('No active entry resolved. Nothing to release.'));
13
+ console.log(warningStyle('No active entry resolved. Nothing to release.'));
14
14
  return;
15
15
  }
16
16
  const releasedAt = new Date().toISOString();
@@ -21,7 +21,7 @@ export async function release(options = {}) {
21
21
  if (await fs.pathExists(indexPath)) {
22
22
  let raw = await fs.readFile(indexPath, 'utf8');
23
23
  // Always update dateEnd (replace placeholder OR existing value)
24
- const hasPlaceholder = raw.includes('dateEnd: [DATE_END]');
24
+ const hasPlaceholder = raw.includes('dateEnd: "[DATE_END]"');
25
25
  const dateEndRegex = /dateEnd:.*$/m;
26
26
  if (hasPlaceholder || dateEndRegex.test(raw)) {
27
27
  raw = raw.replace(dateEndRegex, `dateEnd: ${releasedAt}`);
@@ -44,13 +44,13 @@ export async function release(options = {}) {
44
44
  await fs.remove(lockfilePath);
45
45
  }
46
46
  }
47
- console.log(chalk.green(`Released entry: ${active.slug} (via ${active.source})`));
47
+ console.log(successMessage('Released', `entry: ${active.slug} (via ${active.source})`));
48
48
  if (active.startedAt) {
49
49
  const elapsed = formatElapsed(new Date(active.startedAt), new Date(releasedAt));
50
- console.log(chalk.gray(`Active for ${elapsed}. You may now commit and build.`));
50
+ console.log(neutral(`Active for ${elapsed}. You may now commit and build.`));
51
51
  }
52
52
  else {
53
- console.log(chalk.gray(`Released at ${releasedAt}. You may now commit and build.`));
53
+ console.log(neutral(`Released at ${releasedAt}. You may now commit and build.`));
54
54
  }
55
55
  }
56
56
  function formatElapsed(from, to) {
@@ -1,10 +1,11 @@
1
1
  import fs from 'fs-extra';
2
2
  import { join } from 'node:path';
3
3
  import { execSync } from 'node:child_process';
4
- import chalk from 'chalk';
4
+ import { error as errorStyle, warning as warningStyle, neutral, header, successMessage } from '../lib/theme.js';
5
5
  import matter from 'gray-matter';
6
- import { getConfig } from '../lib/config.js';
6
+ import { getConfig, getLogbookDirPath } from '../lib/config.js';
7
7
  import { getActiveEntry } from '../lib/session.js';
8
+ import { getEntryPath } from '../lib/entry-paths.js';
8
9
  import { LOCKFILE_NAME } from '../lib/lockfile.js';
9
10
  function getGitUsername() {
10
11
  try {
@@ -22,31 +23,31 @@ export async function start(id) {
22
23
  // 1. Enforce single active entry
23
24
  if (await fs.pathExists(lockfilePath)) {
24
25
  const existing = await fs.readJson(lockfilePath);
25
- console.error(chalk.red(`Error: Entry '${existing.slug}' is already active.`));
26
- console.error(chalk.red(`Run 'logbook release' before starting a new entry.`));
26
+ console.error(errorStyle(`Error: Entry '${existing.slug}' is already active.`));
27
+ console.error(errorStyle(`Run 'logbook release' before starting a new entry.`));
27
28
  process.exit(1);
28
29
  }
29
30
  // 2. Resolve folder by ID prefix (e.g. "LB-5" → "LB-5-jira-support")
30
31
  const config = getConfig();
31
32
  // If a bare number is given (e.g. "19"), auto-prepend the configured jiraPrefix
32
33
  const resolvedId = /^\d+$/.test(id) && config.jiraPrefix ? `${config.jiraPrefix}-${id}` : id;
33
- const logbookDir = join(cwd, config.logbookDir);
34
+ const logbookDir = getLogbookDirPath(config, cwd);
34
35
  const allDirs = await fs.readdir(logbookDir);
35
36
  const matchingDir = allDirs.find((d) => {
36
37
  const prefix = d.split('-').slice(0, resolvedId.split('-').length).join('-');
37
38
  return prefix.toLowerCase() === resolvedId.toLowerCase();
38
39
  });
39
40
  if (!matchingDir) {
40
- console.error(chalk.red(`Error: No entry found matching ID '${resolvedId}' in ${config.logbookDir}/.`));
41
- console.error(chalk.red(`Run 'logbook new <id> <slug>' to create it first.`));
41
+ console.error(errorStyle(`Error: No entry found matching ID '${resolvedId}' in ${config.logbookDir}/.`));
42
+ console.error(errorStyle(`Run 'logbook new <id> <slug>' to create it first.`));
42
43
  process.exit(1);
43
44
  }
44
45
  const slug = matchingDir;
45
- const entryDir = join(logbookDir, slug);
46
+ const entryDir = getEntryPath(logbookDir, slug);
46
47
  // Warn if branch-resolved entry is different
47
48
  const activeFromBranch = await getActiveEntry({}, cwd);
48
49
  if (activeFromBranch && activeFromBranch.source === 'branch' && activeFromBranch.slug !== slug) {
49
- console.warn(chalk.yellow(`Warning: Your current Git branch resolves to active entry '${activeFromBranch.slug}', but you are manually starting '${slug}'.`));
50
+ console.warn(warningStyle(`Warning: Your current Git branch resolves to active entry '${activeFromBranch.slug}', but you are manually starting '${slug}'.`));
50
51
  }
51
52
  // 3. Detect git prompter
52
53
  const prompter = getGitUsername();
@@ -65,23 +66,27 @@ export async function start(id) {
65
66
  let raw = await fs.readFile(indexPath, 'utf8');
66
67
  const parsed = matter(raw);
67
68
  // Inject dateStart only if the placeholder exists (preserve existing dateStart on re-start)
68
- // Note: gray-matter parses [DATE_START] as a YAML array, so we check the raw string directly.
69
- if (raw.includes('dateStart: [DATE_START]')) {
70
- raw = raw.replace('dateStart: [DATE_START]', `dateStart: ${lockData.startedAt}`);
69
+ if (raw.includes('dateStart: "[DATE_START]"')) {
70
+ raw = raw.replace('dateStart: "[DATE_START]"', `dateStart: ${lockData.startedAt}`);
71
71
  }
72
72
  // Inject prompter if available and not already set
73
- if (prompter && !parsed.data.prompter) {
74
- raw = raw.replace(/^(---\n[\s\S]*?)(^---$)/m, (_, frontmatter, closing) => {
75
- if (frontmatter.includes('prompter:'))
76
- return _;
77
- return `${frontmatter}prompter: '${prompter.replace(/'/g, "''")}'\n${closing}`;
78
- });
73
+ if (prompter) {
74
+ if (raw.includes('prompter: "[PROMPTER]"')) {
75
+ raw = raw.replace('prompter: "[PROMPTER]"', `prompter: '${prompter.replace(/'/g, "''")}'`);
76
+ }
77
+ else if (!parsed.data.prompter) {
78
+ raw = raw.replace(/^(---\n[\s\S]*?)(^---$)/m, (_, frontmatter, closing) => {
79
+ if (frontmatter.includes('prompter:'))
80
+ return _;
81
+ return `${frontmatter}prompter: '${prompter.replace(/'/g, "''")}'\n${closing}`;
82
+ });
83
+ }
79
84
  }
80
85
  await fs.writeFile(indexPath, raw);
81
86
  }
82
- console.log(chalk.green(`Started entry: ${slug}`));
87
+ console.log(successMessage('Started', `entry: ${slug}`));
83
88
  if (prompter) {
84
- console.log(chalk.blue(`Prompter set to: ${prompter}`));
89
+ console.log(header(`Prompter set to: ${prompter}`));
85
90
  }
86
- console.log(chalk.gray(`Lockfile written to ${LOCKFILE_NAME}. Run 'logbook release' when done.`));
91
+ console.log(neutral(`Lockfile written to ${LOCKFILE_NAME}. Run 'logbook release' when done.`));
87
92
  }
@@ -0,0 +1 @@
1
+ export declare function status(): Promise<void>;
@@ -0,0 +1,138 @@
1
+ import fs from 'fs-extra';
2
+ import { join } from 'node:path';
3
+ import { getConfig, getLogbookDirPath } from '../lib/config.js';
4
+ import { getLogbookEntries } from '../utils/fs.js';
5
+ import { getActiveEntry } from '../lib/session.js';
6
+ import { parseTicketId } from '../utils/id.js';
7
+ import { error, neutral, highlight, bold, warning } from '../lib/theme.js';
8
+ import { getChangedLOC } from '../lib/git-helpers.js';
9
+ import { getLastLogEntry } from '../utils/log-timeline.js';
10
+ export async function status() {
11
+ const config = getConfig();
12
+ const logbookDir = getLogbookDirPath(config);
13
+ if (!(await fs.pathExists(logbookDir))) {
14
+ console.error(error(`Error: Logbook directory '${config.logbookDir}' not found. Run 'logbook init' first.`));
15
+ process.exit(1);
16
+ }
17
+ // Detect currently active entry (if any)
18
+ const active = await getActiveEntry();
19
+ const activeSlug = active?.slug;
20
+ const logbookEntries = await getLogbookEntries(logbookDir);
21
+ let totalCount = logbookEntries.length;
22
+ let draftCount = 0;
23
+ let doneCount = 0;
24
+ let activeCount = 0;
25
+ for (const entry of logbookEntries) {
26
+ const isActive = activeSlug === entry.slug;
27
+ if (isActive) {
28
+ activeCount++;
29
+ }
30
+ if (!entry.hasIndex) {
31
+ draftCount++;
32
+ continue;
33
+ }
34
+ const { data, content } = entry;
35
+ // Check frontmatter field values for bracket-style unfilled placeholders
36
+ const dataValues = Object.values(data)
37
+ .filter((v) => typeof v === 'string')
38
+ .join('\n');
39
+ const frontmatterHasPlaceholders = dataValues.includes('[DATE_END]') ||
40
+ dataValues.includes('[DATE_START]') ||
41
+ dataValues.includes('[WRITE_SUMMARY_HERE]') ||
42
+ dataValues.includes('[PROMPTER]') ||
43
+ dataValues.includes('[HARNESS]') ||
44
+ dataValues.includes('[LLM]');
45
+ // Check body content for unfilled template hints (strip inline code spans to avoid false positives)
46
+ const contentWithoutCode = content.replace(/`[^`]*`/g, '');
47
+ const bodyHasPlaceholders = contentWithoutCode.includes('TODO:') ||
48
+ content.includes('Write a polished, highly readable "short story" of the change here.');
49
+ const hasPlaceholders = frontmatterHasPlaceholders || bodyHasPlaceholders;
50
+ if (hasPlaceholders) {
51
+ draftCount++;
52
+ }
53
+ else if (!isActive) {
54
+ doneCount++;
55
+ }
56
+ }
57
+ // Find latest entry (sorted descending by ticket id / slug)
58
+ const sortedEntries = [...logbookEntries].sort((a, b) => {
59
+ const idA = parseTicketId(a.slug);
60
+ const idB = parseTicketId(b.slug);
61
+ if (idA && idB) {
62
+ if (idA.prefix !== idB.prefix) {
63
+ return idB.prefix.localeCompare(idA.prefix);
64
+ }
65
+ return idB.number - idA.number;
66
+ }
67
+ return b.slug.localeCompare(a.slug);
68
+ });
69
+ const latestEntry = sortedEntries[0];
70
+ let latestText = neutral('None');
71
+ if (latestEntry) {
72
+ const latestTitle = latestEntry.data?.title || latestEntry.slug.replace(/^[A-Za-z]+-\d+-/, '').replace(/-/g, ' ');
73
+ latestText = `${highlight(latestEntry.slug)} - ${latestTitle}`;
74
+ }
75
+ // Print Active Ticket section
76
+ console.log(`\n${bold.underline('Logbook Status')}`);
77
+ console.log(`\n${bold('Active Ticket:')}`);
78
+ if (active) {
79
+ const activeDetail = logbookEntries.find((e) => e.slug === active.slug);
80
+ const activeTitle = activeDetail?.data?.title || active.slug.replace(/^[A-Za-z]+-\d+-/, '').replace(/-/g, ' ');
81
+ console.log(` ${bold('Slug/ID:')} ${highlight(active.slug)}`);
82
+ console.log(` ${bold('Title:')} ${activeTitle}`);
83
+ console.log(` ${bold('Source:')} ${warning(active.source)}`);
84
+ if (active.startedAt) {
85
+ console.log(` ${bold('Started:')} ${active.startedAt}`);
86
+ }
87
+ if (active.prompter) {
88
+ console.log(` ${bold('Prompter:')} ${active.prompter}`);
89
+ }
90
+ // Show last log entry as a nudge to keep logging
91
+ const logPath = join(logbookDir, active.slug, 'log.md');
92
+ if (await fs.pathExists(logPath)) {
93
+ const logContent = await fs.readFile(logPath, 'utf8');
94
+ const lastEntry = getLastLogEntry(logContent);
95
+ if (lastEntry) {
96
+ const truncated = lastEntry.message.length > 80 ? lastEntry.message.slice(0, 77) + '...' : lastEntry.message;
97
+ console.log(` ${bold('Last Log:')} ${lastEntry.isoTimestamp}: ${truncated}`);
98
+ console.log(` ${neutral("→ Use 'logbook log \"<message>\"' if there's anything to add.")}`);
99
+ }
100
+ }
101
+ }
102
+ else {
103
+ console.log(` ${neutral('No active ticket detected.')}`);
104
+ }
105
+ // Calculate changed LOC
106
+ try {
107
+ const summary = await getChangedLOC(config.logbookDir);
108
+ const activeLOC = `${summary.total} (+${summary.insertions}, -${summary.deletions})`;
109
+ console.log(`\n${bold('Changed LOC Count:')} ${highlight(activeLOC)}\n`);
110
+ }
111
+ catch { }
112
+ // Print Settings section
113
+ console.log(`\n${bold('Settings (.project-logbook):')}`);
114
+ console.log(` ${bold('Project Name:')} ${config.projectName}`);
115
+ console.log(` ${bold('Logbook Directory:')} ${config.logbookDir}`);
116
+ console.log(` ${bold('Output Directory:')} ${config.outputDir}`);
117
+ console.log(` ${bold('Primary Color:')} ${config.primaryColor}`);
118
+ if (config.jiraBaseUrl) {
119
+ console.log(` ${bold('Jira Base URL:')} ${config.jiraBaseUrl}`);
120
+ }
121
+ if (config.jiraPrefix) {
122
+ console.log(` ${bold('Jira Prefix:')} ${config.jiraPrefix}`);
123
+ }
124
+ if (config.repositoryUrl) {
125
+ console.log(` ${bold('Repository URL:')} ${config.repositoryUrl}`);
126
+ }
127
+ if (config.tags?.allowed) {
128
+ console.log(` ${bold('Allowed Tags:')} ${config.tags.allowed.join(', ')}`);
129
+ }
130
+ // Print Stats section
131
+ console.log(`\n${bold('Logbook stats:')}`);
132
+ console.log(` ${bold('Total Entries:')} ${totalCount}`);
133
+ console.log(` ${bold('Active:')} ${activeCount}`);
134
+ console.log(` ${bold('Done:')}. ${doneCount}`);
135
+ console.log(` ${bold('Drafts:')} ${draftCount}`);
136
+ console.log(` ${bold('Latest Entry:')} ${latestText}`);
137
+ console.log('');
138
+ }
@@ -1,22 +1,22 @@
1
1
  import fs from 'fs-extra';
2
2
  import { join } from 'node:path';
3
- import chalk from 'chalk';
3
+ import { warning as warningStyle, header, error as errorStyle, success, errorMessage, bold, highlight, } from '../lib/theme.js';
4
4
  import { getTemplatesDir } from '../lib/migrations.js';
5
5
  export async function steer() {
6
6
  const steerPath = join(getTemplatesDir(), 'steer.txt');
7
7
  if (!fs.existsSync(steerPath)) {
8
- console.error(chalk.red('Error: Steering template not found.'));
8
+ console.error(errorMessage('Error', 'Steering template not found.'));
9
9
  return;
10
10
  }
11
11
  const protocol = fs.readFileSync(steerPath, 'utf8');
12
12
  // Add some color to headers and mandatory parts
13
13
  const formatted = protocol
14
- .replace(/^PROJECT LOGBOOK:.+$/m, (m) => chalk.bold.cyan(m))
15
- .replace(/^Phase \d:.+$/gm, (m) => chalk.bold(m))
16
- .replace(/logbook \w+/g, (m) => chalk.green(m))
17
- .replace(/\w+\.md/g, (m) => chalk.blue(m))
18
- .replace(/Mandatory:/g, chalk.yellow('Mandatory:'))
19
- .replace(/Storytelling Mode:/g, chalk.yellow('Storytelling Mode:'))
20
- .replace(/Quality Gate:/g, chalk.red('Quality Gate:'));
14
+ .replace(/^PROJECT LOGBOOK:.+$/m, (m) => bold(highlight(m)))
15
+ .replace(/^Phase \d:.+$/gm, (m) => bold(m))
16
+ .replace(/logbook \w+/g, (m) => success(m))
17
+ .replace(/\w+\.md/g, (m) => header(m))
18
+ .replace(/Mandatory:/g, warningStyle('Mandatory:'))
19
+ .replace(/Storytelling Mode:/g, warningStyle('Storytelling Mode:'))
20
+ .replace(/Quality Gate:/g, errorStyle('Quality Gate:'));
21
21
  console.log(formatted);
22
22
  }
@@ -1,23 +1,23 @@
1
1
  import fs from 'fs-extra';
2
- import chalk from 'chalk';
2
+ import { success, header } from '../lib/theme.js';
3
3
  import { getProjectStatus } from '../lib/migrations.js';
4
4
  export async function upgrade() {
5
5
  const projectStatus = await getProjectStatus();
6
6
  let updatedCount = 0;
7
7
  for (const file of projectStatus) {
8
8
  if (file.status === 'UP_TO_DATE') {
9
- console.log(chalk.blue(`[UP TO DATE] ${file.name}`));
9
+ console.log(header(`[UP TO DATE] ${file.name}`));
10
10
  }
11
11
  else {
12
12
  await fs.writeFile(file.localPath, file.templateContent);
13
- console.log(chalk.green(`[${file.status === 'MISSING' ? 'CREATED' : 'UPDATED'}] ${file.name}`));
13
+ console.log(success(`[${file.status === 'MISSING' ? 'CREATED' : 'UPDATED'}] ${file.name}`));
14
14
  updatedCount++;
15
15
  }
16
16
  }
17
17
  if (updatedCount === 0) {
18
- console.log(chalk.blue('\nEverything is already up to date.'));
18
+ console.log(header('\nEverything is already up to date.'));
19
19
  }
20
20
  else {
21
- console.log(chalk.green(`\nSuccessfully upgraded ${updatedCount} files.`));
21
+ console.log(success(`\nSuccessfully upgraded ${updatedCount} files.`));
22
22
  }
23
23
  }
package/dist/index.js CHANGED
@@ -1,14 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from 'commander';
3
- import { readFileSync } from 'node:fs';
4
- import { join, dirname } from 'node:path';
5
- import { fileURLToPath } from 'node:url';
6
- const __filename = fileURLToPath(import.meta.url);
7
- const __dirname = dirname(__filename);
8
- const pkgPath = join(__dirname, '..', 'package.json');
9
- const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
3
+ import { getPackageVersion } from './lib/package-version.js';
10
4
  const program = new Command();
11
- program.name('logbook').description('A CLI tool for managing project logbooks.').version(pkg.version);
5
+ program.name('logbook').description('A CLI tool for managing project logbooks.').version(getPackageVersion());
12
6
  program
13
7
  .command('init')
14
8
  .description('Initialize .project-logbook config and /logbook folder')
@@ -74,6 +68,13 @@ program
74
68
  const { list } = await import('./commands/list.js');
75
69
  await list(options);
76
70
  });
71
+ program
72
+ .command('status')
73
+ .description('Show current active logbook task, configuration settings, and statistics')
74
+ .action(async () => {
75
+ const { status } = await import('./commands/status.js');
76
+ await status();
77
+ });
77
78
  program
78
79
  .command('log <message>')
79
80
  .description('Append a timestamped log entry to the active log.md (e.g. logbook log "Did a thing")')
@@ -1,61 +1,16 @@
1
1
  import fs from 'fs-extra';
2
- import { join } from 'node:path';
3
- import { unified } from 'unified';
4
- import remarkParse from 'remark-parse';
5
- import remarkGfm from 'remark-gfm';
6
- import remarkRehype from 'remark-rehype';
7
- import rehypeSlug from 'rehype-slug';
8
- import rehypeFormat from 'rehype-format';
9
- import rehypeStringify from 'rehype-stringify';
2
+ import { join, resolve } from 'node:path';
10
3
  import matter from 'gray-matter';
11
4
  import { layout, postTemplate } from './templates.js';
12
5
  import { getGitCommits } from './git-helpers.js';
6
+ import { createGeneralMarkdownProcessor, createEntryMarkdownProcessor, rehypeRewriteMdLinks, } from './markdown-processors.js';
7
+ import { isExternalUrl } from './url-helpers.js';
8
+ import { readFileIfExists, pathExistsOrNull } from '../utils/fs.js';
9
+ import { getEntryFilePaths } from './entry-paths.js';
13
10
  import { mdToHtmlWithImages, extractImagePathsFromMarkdown, copyImages, rehypeRewriteImagePaths, } from './image-helpers.js';
14
- /** Rehype plugin: rewrite relative .md links to /index.html equivalents. */
15
- const rehypeRewriteMdLinks = () => {
16
- return (tree) => {
17
- visitLinks(tree, (node) => {
18
- const href = node.properties?.href;
19
- if (typeof href !== 'string')
20
- return;
21
- if (/^[a-z][a-z\d+\-.]*:/i.test(href) || href.startsWith('#'))
22
- return;
23
- const mdMatch = href.match(/^(.*?)\.md(#.*)?$/i);
24
- if (!mdMatch)
25
- return;
26
- const base = mdMatch[1];
27
- const fragment = mdMatch[2] ?? '';
28
- node.properties.href = `${base}/index.html${fragment}`;
29
- });
30
- };
31
- };
32
- function visitLinks(node, visitor) {
33
- for (const child of node.children) {
34
- if (child.type === 'element') {
35
- if (child.tagName === 'a')
36
- visitor(child);
37
- visitLinks(child, visitor);
38
- }
39
- }
40
- }
41
- const processor = unified()
42
- .use(remarkParse)
43
- .use(remarkGfm)
44
- .use(remarkRehype)
45
- .use(rehypeSlug)
46
- .use(rehypeRewriteMdLinks)
47
- .use(rehypeFormat)
48
- .use(rehypeStringify);
49
- /** Processor for entry content with image path rewriting */
50
- const entryProcessor = unified()
51
- .use(remarkParse)
52
- .use(remarkGfm)
53
- .use(remarkRehype)
54
- .use(rehypeSlug)
55
- .use(rehypeRewriteMdLinks)
56
- .use(rehypeRewriteImagePaths)
57
- .use(rehypeFormat)
58
- .use(rehypeStringify);
11
+ import { transformLogToTimeline } from '../utils/log-timeline.js';
12
+ const processor = createGeneralMarkdownProcessor(rehypeRewriteMdLinks);
13
+ const entryProcessor = createEntryMarkdownProcessor(rehypeRewriteMdLinks, rehypeRewriteImagePaths);
59
14
  export async function mdToHtml(md) {
60
15
  const result = await processor.process(md);
61
16
  return result.toString();
@@ -103,18 +58,24 @@ async function renderLinkedMdFiles(markdownSources, entryPath, entryOutputDir, c
103
58
  const href = raw.split('#')[0];
104
59
  if (!href)
105
60
  continue;
106
- if (/^[a-z][a-z\d+\-.]*:/i.test(href))
61
+ if (isExternalUrl(href))
107
62
  continue;
108
63
  if (seen.has(href))
109
64
  continue;
110
65
  seen.add(href);
111
66
  let sourcePath = join(entryPath, href);
112
- if (!(await fs.pathExists(sourcePath)))
113
- sourcePath = join(process.cwd(), href);
114
- if (!(await fs.pathExists(sourcePath))) {
67
+ sourcePath = (await pathExistsOrNull(sourcePath)) ?? join(process.cwd(), href);
68
+ if (!sourcePath || !(await pathExistsOrNull(sourcePath))) {
115
69
  console.warn(` Linked file not found, skipping: ${href}`);
116
70
  continue;
117
71
  }
72
+ // Path traversal protection: ensure resolved path stays within project boundaries
73
+ const resolvedPath = resolve(sourcePath);
74
+ const projectRoot = resolve(process.cwd());
75
+ if (!resolvedPath.startsWith(projectRoot + '/') && resolvedPath !== projectRoot) {
76
+ console.warn(` Path traversal blocked: ${href}`);
77
+ continue;
78
+ }
118
79
  const mdContent = await fs.readFile(sourcePath, 'utf8');
119
80
  const bodyHtml = await mdToHtml(mdContent);
120
81
  const title = href.replace(/\.md$/i, '');
@@ -135,12 +96,11 @@ async function renderLinkedMdFiles(markdownSources, entryPath, entryOutputDir, c
135
96
  }
136
97
  }
137
98
  export async function renderPost(data, i, allEntries, ctx) {
138
- const entryPath = join(ctx.logbookDir, data.slug);
139
- const ticketPath = join(entryPath, 'ticket.md');
140
- const logPath = join(entryPath, 'log.md');
141
- const { content, content: summaryContent } = matter(await fs.readFile(join(entryPath, 'index.md'), 'utf8'));
142
- const ticketRaw = (await fs.pathExists(ticketPath)) ? await fs.readFile(ticketPath, 'utf8') : '';
143
- const logRaw = (await fs.pathExists(logPath)) ? await fs.readFile(logPath, 'utf8') : '';
99
+ const entryFilePaths = getEntryFilePaths(ctx.logbookDir, data.slug);
100
+ const entryPath = entryFilePaths.index.replace(/\/index\.md$/, '');
101
+ const { content, content: summaryContent } = matter(await fs.readFile(entryFilePaths.index, 'utf8'));
102
+ const ticketRaw = await readFileIfExists(entryFilePaths.ticket);
103
+ const logRaw = await readFileIfExists(entryFilePaths.log);
144
104
  // Process with image collection for index.md content
145
105
  const { html: storyHtml, imagePaths: storyImages } = await mdToHtmlWithImages(content.replace(/^#\s+.+$/m, '').trim());
146
106
  // Collect images from all markdown sources
@@ -151,16 +111,19 @@ export async function renderPost(data, i, allEntries, ctx) {
151
111
  const jiraUrl = ctx.config.jiraBaseUrl && data.ticket ? `${ctx.config.jiraBaseUrl}${data.ticket}` : undefined;
152
112
  const prev = i > 0 ? allEntries[i - 1] : null;
153
113
  const next = i < allEntries.length - 1 ? allEntries[i + 1] : null;
154
- const postContent = postTemplate({
114
+ // Transform log to timeline if possible, otherwise fall back to plain markdown
115
+ const logHtml = logRaw ? await transformLogToTimeline(logRaw) : '';
116
+ const { header: postHeader, content: postMainContent } = postTemplate({
155
117
  ...data,
156
118
  title: data.title ?? data.slug,
157
119
  harness: data.harness ?? '',
158
120
  content: storyHtml,
159
121
  ticketHtml: ticketRaw ? await mdToHtmlWithImagePathRewrite(ticketRaw) : '',
160
- logHtml: logRaw ? await mdToHtmlWithImagePathRewrite(logRaw) : '',
122
+ logHtml,
161
123
  commits,
162
124
  version: ctx.version,
163
125
  jiraUrl,
126
+ repositoryUrl: ctx.config.repositoryUrl,
164
127
  prevEntry: prev ? { slug: prev.slug, title: prev.title ?? '', ticket: prev.ticket } : null,
165
128
  nextEntry: next ? { slug: next.slug, title: next.title ?? '', ticket: next.ticket } : null,
166
129
  });
@@ -173,8 +136,8 @@ export async function renderPost(data, i, allEntries, ctx) {
173
136
  description: descriptionRaw.substring(0, 160),
174
137
  bodySlug: data.slug,
175
138
  buildMeta,
176
- header: postContent.split('</header>')[0] + '</header>',
177
- content: postContent.split('</header>')[1],
139
+ header: postHeader,
140
+ content: postMainContent,
178
141
  });
179
142
  const entryOutputDir = join(ctx.outputDir, data.slug);
180
143
  await fs.mkdirp(entryOutputDir);
@@ -0,0 +1,20 @@
1
+ import type { LogbookConfig } from './config.js';
2
+ /**
3
+ * Set up the output directory: create it, copy static assets (favicon, styles, script).
4
+ */
5
+ export declare function setupOutputDirectory(outputDir: string, config: LogbookConfig): Promise<void>;
6
+ /**
7
+ * Process README.md if it exists and return rendered HTML + image paths.
8
+ */
9
+ export declare function processReadme(projectRoot: string): Promise<{
10
+ html: string;
11
+ imagePaths: string[];
12
+ }>;
13
+ /**
14
+ * Copy README images to the output directory.
15
+ */
16
+ export declare function copyReadmeImages(projectRoot: string, outputDir: string, imagePaths: string[]): Promise<void>;
17
+ /**
18
+ * Process the About content and return rendered HTML.
19
+ */
20
+ export declare function processAboutContent(aboutContent: string): Promise<string>;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Helper functions for the build command.
3
+ * Breaks down the monolithic build() function into testable, reusable steps.
4
+ */
5
+ import fs from 'fs-extra';
6
+ import { join } from 'node:path';
7
+ import { warning } from './theme.js';
8
+ import { URL } from 'node:url';
9
+ import { mdToHtmlWithImages, copyImages } from './image-helpers.js';
10
+ import { getStyles } from './styles.js';
11
+ import { getClientScript } from './logbook-client.js';
12
+ import { mdToHtml } from './build-helpers.js';
13
+ /**
14
+ * Set up the output directory: create it, copy static assets (favicon, styles, script).
15
+ */
16
+ export async function setupOutputDirectory(outputDir, config) {
17
+ await fs.remove(outputDir);
18
+ await fs.mkdirp(outputDir);
19
+ await fs.copyFile(new URL('../templates/favicon.svg', import.meta.url), join(outputDir, 'favicon.svg'));
20
+ await fs.writeFile(join(outputDir, 'style.css'), getStyles(config.primaryColor));
21
+ await fs.writeFile(join(outputDir, 'logbook.js'), getClientScript());
22
+ }
23
+ /**
24
+ * Process README.md if it exists and return rendered HTML + image paths.
25
+ */
26
+ export async function processReadme(projectRoot) {
27
+ const readmePath = join(projectRoot, 'README.md');
28
+ let readmeHtml = '';
29
+ let readmeImages = [];
30
+ try {
31
+ if (await fs.pathExists(readmePath)) {
32
+ const readmeContent = await fs.readFile(readmePath, 'utf8');
33
+ const { html, imagePaths } = await mdToHtmlWithImages(readmeContent);
34
+ readmeHtml = html;
35
+ readmeImages = imagePaths;
36
+ }
37
+ }
38
+ catch (error) {
39
+ console.warn(warning(`Warning: Failed to read README.md: ${error instanceof Error ? error.message : error}`));
40
+ readmeHtml = '<p>README unavailable.</p>';
41
+ }
42
+ return { html: readmeHtml, imagePaths: readmeImages };
43
+ }
44
+ /**
45
+ * Copy README images to the output directory.
46
+ */
47
+ export async function copyReadmeImages(projectRoot, outputDir, imagePaths) {
48
+ if (imagePaths.length > 0) {
49
+ await copyImages(projectRoot, outputDir, imagePaths);
50
+ }
51
+ }
52
+ /**
53
+ * Process the About content and return rendered HTML.
54
+ */
55
+ export async function processAboutContent(aboutContent) {
56
+ return await mdToHtml(aboutContent);
57
+ }
@@ -6,9 +6,26 @@ export interface LogbookConfig {
6
6
  primaryColor: string;
7
7
  jiraBaseUrl?: string;
8
8
  jiraPrefix?: string;
9
+ repositoryUrl?: string;
9
10
  tags?: {
10
11
  allowed: string[];
11
12
  };
12
13
  }
13
14
  export declare const DEFAULT_CONFIG: LogbookConfig;
14
15
  export declare function getConfig(cwd?: string): LogbookConfig;
16
+ /**
17
+ * Get the absolute path to the logbook directory.
18
+ * Convenience function to avoid repeating: join(process.cwd(), config.logbookDir)
19
+ * @param config - The logbook config
20
+ * @param cwd - Optional working directory (defaults to process.cwd())
21
+ * @returns Absolute path to the logbook directory
22
+ */
23
+ export declare function getLogbookDirPath(config: LogbookConfig, cwd?: string): string;
24
+ /**
25
+ * Get the absolute path to the output directory.
26
+ * Convenience function to avoid repeating: join(process.cwd(), config.outputDir)
27
+ * @param config - The logbook config
28
+ * @param cwd - Optional working directory (defaults to process.cwd())
29
+ * @returns Absolute path to the output directory
30
+ */
31
+ export declare function getOutputDirPath(config: LogbookConfig, cwd?: string): string;